Example usage for java.util.concurrent ExecutorService shutdown

List of usage examples for java.util.concurrent ExecutorService shutdown

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService shutdown.

Prototype

void shutdown();

Source Link

Document

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

Usage

From source file:at.tfr.securefs.client.SecurefsClient.java

public static void main(String[] args) throws Exception {

    SecurefsClient client = new SecurefsClient();
    try {//from  w  ww . j a v a 2  s.c  o m
        client.parse(args);

        if (client.asyncTest) {
            ExecutorService executor = Executors.newFixedThreadPool(client.threads);
            for (int i = 0; i < client.threads; i++) {
                executor.submit(client);
            }
            executor.shutdown();
            executor.awaitTermination(10, TimeUnit.MINUTES);
        } else {
            client.run();
        }

    } catch (Throwable e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(SecurefsClient.class.getSimpleName(), client.options);
        e.printStackTrace();
    }
}

From source file:CallableTask.java

public static void main(String[] args) throws Exception {
    // Get an executor with three threads in its thread pool
    ExecutorService exec = Executors.newFixedThreadPool(3);
    CallableTask task = new CallableTask(1);
    // Submit the callable task to executor
    Future<Integer> submittedTask = exec.submit(task);

    Integer result = submittedTask.get();
    System.out.println("Task's total  sleep time: " + result + "  seconds");
    exec.shutdown();
}

From source file:at.tfr.securefs.client.SecurefsFileServiceClient.java

public static void main(String[] args) throws Exception {

    SecurefsFileServiceClient client = new SecurefsFileServiceClient();
    try {/*from ww  w  .  j av  a  2  s  . c o m*/
        client.parse(args);

        if (client.asyncTest) {
            ExecutorService executor = Executors.newFixedThreadPool(client.threads);
            for (int i = 0; i < client.threads; i++) {
                executor.submit(client);
            }
            executor.shutdown();
            executor.awaitTermination(10, TimeUnit.MINUTES);
        } else {
            client.run();
        }

    } catch (Throwable e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(SecurefsFileServiceClient.class.getSimpleName(), client.options);
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    ExecutorService executor = Executors.newCachedThreadPool();
    Future<?> future = executor.submit(() -> {
        try {//  w w  w. j av a2 s.  c  o m
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println("Epic fail.");
        }
    });
    System.out.println("Waiting for task to finish..");
    future.get();
    System.out.println("Task finished!");
    executor.shutdown();
}

From source file:Main.java

public static void main(String[] args) {
    Callable<Object> badTask = () -> {
        throw new RuntimeException("Throwing exception from task execution...");
    };/*from   w  ww  .j av  a  2s .  com*/
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Future submittedTask = exec.submit(badTask);
    try {
        Object result = submittedTask.get();
    } catch (ExecutionException e) {
        System.out.println(e.getMessage());
        System.out.println(e.getCause().getMessage());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    exec.shutdown();
}

From source file:jsonclient.JsonClient.java

public static void main(String args[]) {

    int EPS = 1;/*ww w.  ja va  2 s  .  com*/
    List<Place> countries = new ArrayList<Place>();
    List<Thread> threads = new ArrayList<Thread>();
    Country country;
    countries = getCountries();
    //CountrySearcher countrySearcher = null;
    Iterator<Place> itrCountry = countries.iterator();
    ExecutorService exec = Executors.newFixedThreadPool(4);

    while (itrCountry.hasNext()) {
        country = new Country(itrCountry.next());
        CountrySearcher cs = new CountrySearcher(country, EPS);
        threads.add(cs.thread);
        exec.execute(cs);
    }

    exec.shutdown();

    for (Thread th : threads)
        try {
            th.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(JsonClient.class.getName()).log(Level.SEVERE, null, ex);
        }

}

From source file:SimpExec.java

public static void main(String args[]) {
    CountDownLatch cdl = new CountDownLatch(5);
    CountDownLatch cdl2 = new CountDownLatch(5);
    CountDownLatch cdl3 = new CountDownLatch(5);
    CountDownLatch cdl4 = new CountDownLatch(5);
    ExecutorService es = Executors.newFixedThreadPool(2);

    es.execute(new MyThread(cdl, "A"));
    es.execute(new MyThread(cdl2, "B"));
    es.execute(new MyThread(cdl3, "C"));
    es.execute(new MyThread(cdl4, "D"));

    try {//  ww w  .  ja  v  a2 s  .  c o m
        cdl.await();
        cdl2.await();
        cdl3.await();
        cdl4.await();
    } catch (InterruptedException exc) {
        System.out.println(exc);
    }

    es.shutdown();
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java

public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();

    // Most of the following defaults should be changed in
    // the --conf or "conf.properties" file
    String sqlURL = null;/*from w  ww. j a v  a  2s  . c om*/
    String sqlUser = null;
    String sqlPass = null;
    String sqlDb = null;
    String sqlHost = "127.0.0.1";
    String backupDirStr = null;
    String laterThanStr = "";
    String fullBackupPathStr = null;
    String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak";
    String fullBackupDatePatternStr = "yyyyMMddHHmm";
    String sqlProcessUser = null;
    String logBackupPatternStr = "(.*)\\.trn";
    String logBackupDatePatternStr = "yyyyMMddHHmmss";

    boolean doFullRestore = false;
    Boolean useLogFileLastMode = null;
    Boolean monitorLogBackupDir = null;

    options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build());

    options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build());

    options.addOption(Option.builder().longOpt("restore-full")
            .desc("Restore the full backup before continuing.").build());

    options.addOption(Option.builder().longOpt("use-lastmod")
            .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build());

    options.addOption(Option.builder().longOpt("monitor-backup-dir")
            .desc("Monitor the backup directory for new log backups, and apply them.").build());

    CommandLine line = null;
    try {
        try {
            line = parser.parse(options, args);
        } catch (ParseException ex) {
            throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()),
                    ex);
        }

        String confFile = null;

        // Process the command line arguments
        Iterator cmdI = line.iterator();
        while (cmdI.hasNext()) {
            Option currOpt = (Option) cmdI.next();
            String currOptName = currOpt.getLongOpt();

            switch (currOptName) {
            case "conf":
                // Parse the configuration file
                confFile = currOpt.getValue();
                break;

            case "laterthan":
                // "Later Than" file date filter
                laterThanStr = currOpt.getValue();
                break;

            case "restore-full":
                // Do a full backup restore before restoring logs
                doFullRestore = true;
                break;

            case "monitor-backup-dir":
                // Monitor the backup directory for new logs
                monitorLogBackupDir = true;
                break;

            case "use-lastmod":
                // Use the last-modified date on Log Backup files for sorting/filtering
                useLogFileLastMode = true;
                break;
            }
        }

        Properties confProperties = null;

        if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) {
            throw new MSSQLApplyLogException(
                    "Missing or unreadable configuration file.  Please specify --conf");
        } else {
            // Process the conf.properties file
            confProperties = new Properties();
            try {
                confProperties.load(Files.newBufferedReader(Paths.get(confFile)));
            } catch (IOException ex) {
                throw new MSSQLApplyLogException("Error loading properties file", ex);
            }

            sqlURL = confProperties.getProperty("sqlURL", "");
            sqlUser = confProperties.getProperty("sqlUser", "");
            sqlPass = confProperties.getProperty("sqlPass", "");
            sqlDb = confProperties.getProperty("sqlDb", "");
            sqlHost = confProperties.getProperty("sqlHost", "");
            backupDirStr = confProperties.getProperty("backupDir", "");

            if (StringUtils.isBlank(laterThanStr)) {
                laterThanStr = confProperties.getProperty("laterThan", "");
            }

            fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr);
            fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr);
            fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern",
                    fullBackupDatePatternStr);
            sqlProcessUser = confProperties.getProperty("sqlProcessUser", "");

            logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr);
            logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern",
                    logBackupDatePatternStr);

            if (useLogFileLastMode == null) {
                String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false");
                useLogFileLastMode = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr)));
            }

            if (monitorLogBackupDir == null) {
                String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false");
                monitorLogBackupDir = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr)));
            }
        }
    } catch (MSSQLApplyLogException ex) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.append(String.format("Error : '%s'\n\n", ex.getMessage()));

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ",
                    "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options,
                    0, 2, " All Rights Reserved.", true);

            System.out.println(sw.toString());
        } catch (IOException iex) {
            LOGGER.debug("Error processing usage", iex);
        }

        System.exit(1);
    }

    MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr,
            fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr,
            logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser,
            useLogFileLastMode, doFullRestore, monitorLogBackupDir);

    MSSQLApplyLog logProc = MSSQLApplyLog.from(config);

    BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build();

    ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory);

    Future<Integer> currRunTask = mainThreadExe.submit(logProc);

    mainThreadExe.shutdown();

    Integer resp = 0;
    try {
        resp = currRunTask.get();
    } catch (InterruptedException ex) {
        LOGGER.error("Application 'main' thread was interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("Application 'main' thread execution error", ex);
    } finally {
        // If main leaves for any reason, shutdown all threads
        mainThreadExe.shutdownNow();
    }

    System.exit(resp);
}

From source file:ThreadPoolTest.java

public static void main(String[] args) throws Exception {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");
    String directory = in.nextLine();
    System.out.print("Enter keyword (e.g. volatile): ");
    String keyword = in.nextLine();

    ExecutorService pool = Executors.newCachedThreadPool();

    MatchCounter counter = new MatchCounter(new File(directory), keyword, pool);
    Future<Integer> result = pool.submit(counter);

    try {//from   w ww.j  a va2  s  . com
        System.out.println(result.get() + " matching files.");
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
    }
    pool.shutdown();

    int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize();
    System.out.println("largest pool size=" + largestPoolSize);
}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

public static void main(String[] args) throws IOException, InterruptedException {

    /* Command line options */
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);/* w  w  w .jav a 2  s.  co m*/
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}