Example usage for java.util.concurrent ThreadPoolExecutor awaitTermination

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:Test.java

public static void main(String[] args) throws InterruptedException {
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    for (int i = 0; i < 10; i++) {
        final int localI = i;
        queue.add(new Runnable() {
            public void run() {
                doExpensiveOperation(localI);
            }/*from   w  w  w . j  ava 2 s .  c  om*/
        });
    }
    ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, queue);
    executor.prestartAllCoreThreads();
    executor.shutdown();
    executor.awaitTermination(100000, TimeUnit.SECONDS);
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

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

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);/* ww w . j av  a2 s  .c  o  m*/
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:Main.java

public static void shutdownPoolAndAwaitTermination(ThreadPoolExecutor pool) {
    try {//from  w  w  w  .  java  2 s .c o  m
        pool.shutdown();
        pool.awaitTermination(1000, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * @param exec// w ww.  j a v a2  s  .  co m
 * @param checkInterval
 * @param shutdown
 */
public static void checkBlockPoolCompleted(ThreadPoolExecutor exec, int checkInterval, boolean shutdown) {
    while (true) {
        int activite = exec.getActiveCount();
        waitFor(checkInterval);
        if (activite == 0) {
            break;
        }
    }

    if (shutdown) {
        exec.shutdown();
        try {
            exec.awaitTermination(60, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.qmetry.qaf.automation.integration.ResultUpdator.java

public static void awaitTermination() {
    if (hasActivePool) {
        ThreadPoolExecutor pool = getPool();
        while (pool.getActiveCount() > 0) {
            logger.info("Result updator : Remaining " + pool.getActiveCount() + " result to be update.");
            try {
                pool.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();//ww w  .  ja v a  2 s  .  c o  m
            }
        }
        System.out.println("Result updator : Remaining " + pool.getActiveCount() + " result to be update.");
        try {
            pool.shutdownNow();
        } catch (Exception e) {
            e.printStackTrace();
        }
        hasActivePool = false;
    }
}

From source file:CreateTest.java

static void doTestPool(int nThreads) {
    done = false;/*from w  ww. jav a2  s .  co  m*/
    nCalls = new AtomicInteger(0);
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(nThreads, nThreads, 50000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    Runnable r = new CreateTest();
    for (int i = 0; i < target; i++) {
        tpe.execute(r);
    }
    tpe.shutdown();
    try {
        tpe.awaitTermination(10000000L, TimeUnit.SECONDS);
    } catch (Exception e) {
    }
}

From source file:com.l2jfree.util.concurrent.L2ThreadPool.java

private static boolean awaitTermination(long timeoutInMillisec) throws InterruptedException {
    final long begin = System.currentTimeMillis();

    while (System.currentTimeMillis() - begin < timeoutInMillisec) {
        boolean done = true;

        for (ThreadPoolExecutor threadPool : getThreadPools())
            done &= threadPool.awaitTermination(10, TimeUnit.MILLISECONDS) && threadPool.getActiveCount() == 0;

        if (done)
            return true;
    }//from  w w w .j av  a  2  s.  c om

    return false;
}

From source file:com.alibaba.wasp.fserver.SplitThread.java

private void waitFor(ThreadPoolExecutor t, String name) {
    boolean done = false;
    while (!done) {
        try {/*  ww w  .j a  v a2s .c om*/
            done = t.awaitTermination(60, TimeUnit.SECONDS);
            LOG.debug("Waiting for " + name + " to finish...");
        } catch (InterruptedException ie) {
            LOG.debug("Interrupted waiting for " + name + " to finish...");
        }
    }
}

From source file:com.espertech.esper.core.thread.ThreadingServiceImpl.java

private void stopPool(ThreadPoolExecutor threadPool, BlockingQueue<Runnable> queue, String name) {
    if (log.isInfoEnabled()) {
        log.info("Shutting down pool " + name);
    }//from  w  ww  .j a v a 2 s.  com

    queue.clear();

    threadPool.shutdown();
    try {
        threadPool.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error("Interruped awaiting termination", e);
    }
}

From source file:logicProteinHypernetwork.analysis.complexes.SPINComplexPrediction.java

/**
 * Refine plain network based predicted complexes based on the protein 
 * hypernetwork with a certain ComplexRefinement instance.
 * //w w  w .  j  av a  2 s  .c  o  m
 * @param naiveComplexes the plain network based complexes
 * @param complexRefinement the instance of ComplexRefinement
 */
protected void refinement(final Collection<Complex> naiveComplexes,
        final SPINComplexRefinement complexRefinement) {

    ThreadPoolExecutor threads = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount);

    for (final Complex c : naiveComplexes) {
        threads.submit(new RefineComplex(c, complexRefinement));
    }

    threads.shutdown();
    try {
        threads.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    } catch (InterruptedException ex) {
        System.err.println(ex);
    }

    Set<Complex> unique = new HashSet<Complex>(complexes);
    complexes.clear();
    complexes.addAll(unique);

    //System.out.println("Refined to " + complexes.size() + " complexes");
}