Example usage for java.util.concurrent ExecutorService awaitTermination

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

Introduction

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

Prototype

boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Usage

From source file:Main.java

public static void main(String[] args) throws InterruptedException {
    Main task = new Main();
    int threads = Runtime.getRuntime().availableProcessors();
    ExecutorService pool = Executors.newFixedThreadPool(threads);
    for (int i = 0; i < threads; i++) {
        pool.submit(task);/*from   w  w w  . j av  a  2  s.co  m*/
    }
    pool.awaitTermination(120, TimeUnit.SECONDS);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    System.out.println("Thread pool size = " + MAX_THREADS);
    ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
    Future previousFuture = null;
    for (int i = 0; i < MAX_THREADS; i++) {
        JobRunnable job = new JobRunnable(i, previousFuture);
        previousFuture = executor.submit(job);
    }//from  www  .j  av a2s  .  c  o  m
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    System.out.println("Program done.");
}

From source file:io.rhiot.spec.IoTSpec.java

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

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(Option.builder("c").longOpt(CONFIG).desc(
            "Location of the test configuration file. A default value is 'src/main/resources/test.yaml' for easy IDE testing")
            .hasArg().build());//w  w w .j  a va  2s .com

    options.addOption(Option.builder("i").longOpt(INSTANCE).desc("Instance of the test; A default value is 1")
            .hasArg().build());

    options.addOption(Option.builder("r").longOpt(REPORT)
            .desc("Location of the test report. A default value is 'target/report.csv'").hasArg().build());

    CommandLine line = parser.parse(options, args);
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    TestProfile test = mapper.readValue(new File(line.getOptionValue(CONFIG, "src/main/resources/test.yaml")),
            TestProfile.class);
    int instance = Integer.valueOf(line.getOptionValue(INSTANCE, "1"));
    test.setInstance(instance);
    String report = line.getOptionValue(REPORT, "target/report.csv");
    test.setReport(new CSVReport(report));

    LOG.info("Test '" + test.getName() + "' instance " + instance + " started");
    final List<Driver> drivers = test.getDrivers();
    ExecutorService executorService = Executors.newFixedThreadPool(drivers.size());
    List<Future<Void>> results = executorService.invokeAll(drivers, test.getDuration(), TimeUnit.MILLISECONDS);
    executorService.shutdownNow();
    executorService.awaitTermination(5, TimeUnit.SECONDS);

    results.forEach(result -> {
        try {
            result.get();
        } catch (ExecutionException execution) {
            LOG.warn("Exception running driver", execution);
        } catch (Exception interrupted) {
        }
    });

    drivers.forEach(driver -> {
        driver.stop();

        try {
            test.getReport().print(driver);
        } catch (Exception e) {
            LOG.warn("Failed to write reports for the driver " + driver);
        }
        LOG.debug("Driver " + driver);
        LOG.debug("\t " + driver.getResult());
    });
    test.getReport().close();

    LOG.info("Test '" + test.getName() + "' instance " + instance + " finished");

}

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

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

    SecurefsClient client = new SecurefsClient();
    try {/*from   w w w.  java2  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:at.tfr.securefs.client.SecurefsFileServiceClient.java

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

    SecurefsFileServiceClient client = new SecurefsFileServiceClient();
    try {//from w  w  w.  j av a 2 s.c om
        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:org.jclouds.examples.blobstore.BlobUploaderMain.java

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

    OptionParser parser = new OptionParser();
    parser.accepts("directory").withRequiredArg().required().ofType(String.class);
    parser.accepts("provider").withRequiredArg().required().ofType(String.class);
    parser.accepts("username").withRequiredArg().required().ofType(String.class);
    parser.accepts("password").withRequiredArg().required().ofType(String.class);
    parser.accepts("region").withRequiredArg().required().ofType(String.class);
    parser.accepts("threads").withRequiredArg().ofType(Integer.TYPE).describedAs("number of parallel threads");
    OptionSet options = null;//from   w w  w.j  a v  a  2s. com

    try {
        options = parser.parse(args);
    } catch (OptionException e) {
        System.out.println(e.getLocalizedMessage());
        parser.printHelpOn(System.out);
        return;
    }

    if (options.has("threads")) {
        numThreads = Integer.valueOf((String) options.valueOf("numThreads"));
    }

    File rootDir = new File((String) options.valueOf("directory"));
    Collection<File> files = FileUtils.listFiles(rootDir, CanReadFileFilter.CAN_READ, TrueFileFilter.TRUE);
    totalBytes = FileUtils.sizeOfDirectory(rootDir);

    System.out.println("Uploading " + rootDir.getName() + " " + totalBytes / FileUtils.ONE_MB + "MB");

    ExecutorService executor = Executors.newFixedThreadPool(numThreads);

    for (File f : files) {
        BlobUploader b = new BlobUploader((String) options.valueOf("username"),
                (String) options.valueOf("password"), (String) options.valueOf("provider"),
                (String) options.valueOf("region"), f);
        executor.execute(b);
    }
    executor.shutdown();

    try {
        executor.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.accumulo.server.test.QueryMetadataTable.java

public static void main(String[] args)
        throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
    Option usernameOpt = new Option("username", "username", true, "username");
    Option passwordOpt = new Option("password", "password", true, "password");

    Options opts = new Options();

    opts.addOption(usernameOpt);//from  w w w. ja  v a  2 s .  c  o  m
    opts.addOption(passwordOpt);

    Parser p = new BasicParser();
    CommandLine cl = null;
    try {
        cl = p.parse(opts, args);
    } catch (ParseException e1) {
        System.out.println("Parse Exception, exiting.");
        return;
    }

    if (cl.getArgs().length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("queryMetadataTable <numQueries> <numThreads> ", opts);
        return;
    }
    String[] rargs = cl.getArgs();

    int numQueries = Integer.parseInt(rargs[0]);
    int numThreads = Integer.parseInt(rargs[1]);
    credentials = new AuthInfo(cl.getOptionValue("username", "root"),
            ByteBuffer.wrap(cl.getOptionValue("password", "secret").getBytes()),
            HdfsZooInstance.getInstance().getInstanceID());

    Connector connector = HdfsZooInstance.getInstance().getConnector(credentials.user, credentials.password);
    Scanner scanner = connector.createScanner(Constants.METADATA_TABLE_NAME, Constants.NO_AUTHS);
    scanner.setBatchSize(20000);
    Text mdrow = new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), null));

    HashSet<Text> rowSet = new HashSet<Text>();

    int count = 0;

    for (Entry<Key, Value> entry : scanner) {
        System.out.print(".");
        if (count % 72 == 0) {
            System.out.printf(" %,d\n", count);
        }
        if (entry.getKey().compareRow(mdrow) == 0 && entry.getKey().getColumnFamily()
                .compareTo(Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY) == 0) {
            System.out.println(entry.getKey() + " " + entry.getValue());
            location = entry.getValue().toString();
        }

        if (!entry.getKey().getRow().toString().startsWith(Constants.METADATA_TABLE_ID))
            rowSet.add(entry.getKey().getRow());
        count++;

    }

    System.out.printf(" %,d\n", count);

    ArrayList<Text> rows = new ArrayList<Text>(rowSet);

    Random r = new Random();

    ExecutorService tp = Executors.newFixedThreadPool(numThreads);

    long t1 = System.currentTimeMillis();

    for (int i = 0; i < numQueries; i++) {
        int index = r.nextInt(rows.size());
        MDTQuery mdtq = new MDTQuery(rows.get(index));
        tp.submit(mdtq);
    }

    tp.shutdown();

    try {
        tp.awaitTermination(1, TimeUnit.HOURS);
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    long t2 = System.currentTimeMillis();
    double delta = (t2 - t1) / 1000.0;
    System.out.println("time : " + delta + "  queries per sec : " + (numQueries / delta));
}

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);/*from ww  w  . j a v  a 2 s  .  c  o 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");
}

From source file:DIA_Umpire_To_Skyline.DIA_Umpire_To_Skyline.java

/**
 * @param args the command line arguments
 *///from www  .  j  a v a  2s  .c  om
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire_To_Skyline (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length < 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path NoThreads");
        System.out.println("command : java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path [Option]\n");
        System.out.println("\nOptions");
        System.out.println("\t-t\tNo. of threads, Ex: -t4 (using four threads, default value)");
        System.out.println(
                "\t-cP\tPath of msconvert.exe for mzXML conversion, Ex: -cP (using four threads, default value)");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.DEBUG);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_to_skyline.log");
    } catch (Exception e) {
        System.out.println("Logger initialization failed");
    }

    Logger.getRootLogger().info("Path:" + args[0]);
    String msconvertpath = "C:/inetpub/tpp-bin/msconvert";

    String WorkFolder = args[0];
    int NoCPUs = 4;

    for (int i = 1; i < args.length; i++) {
        if (args[i].startsWith("-")) {
            if (args[i].startsWith("-cP")) {
                msconvertpath = args[i].substring(3);
                Logger.getRootLogger().info("MSConvert path: " + msconvertpath);
            }
            if (args[i].startsWith("-t")) {
                NoCPUs = Integer.parseInt(args[i].substring(2));
                Logger.getRootLogger().info("No. of threads: " + NoCPUs);
            }
        }
    }

    HashMap<String, File> AssignFiles = new HashMap<>();

    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("Path: " + folder.getAbsolutePath() + " cannot be found.");
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile() && fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile() && fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }

        ExecutorService executorPool = null;
        executorPool = Executors.newFixedThreadPool(3);

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            FileThread thread = new FileThread(mzXMLFile, NoCPUs, msconvertpath);
            executorPool.execute(thread);
        }
        executorPool.shutdown();
        try {
            executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            Logger.getRootLogger().info("interrupted..");
        }
    } catch (Exception e) {
        Logger.getRootLogger().error(e.getMessage());
        throw e;
    }
    Logger.getRootLogger().info("Job done");
    Logger.getRootLogger().info(
            "=================================================================================================");

}

From source file:kymr.github.io.future.LoadTest.java

public static void main(String[] args) throws InterruptedException {
    ExecutorService es = Executors.newFixedThreadPool(100);

    RestTemplate rt = new RestTemplate();
    String url = "http://localhost:8080/dr";

    StopWatch main = new StopWatch();
    main.start();/*from   ww  w . j  av  a  2  s .c  o m*/

    for (int i = 0; i < 100; i++) {
        es.execute(() -> {
            int idx = counter.addAndGet(1);
            log.info("Thread {}", idx);

            StopWatch sw = new StopWatch();
            sw.start();

            rt.getForObject(url, String.class);

            sw.stop();
            log.info("Elapsed: {} -> {}", idx, sw.getTotalTimeSeconds());
        });
    }

    es.shutdown();
    es.awaitTermination(100, TimeUnit.SECONDS);

    main.stop();
    log.info("Total: {}", main.getTotalTimeSeconds());
}