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:net.openhft.chronicle.logger.slf4j.Slf4jVanillaChronicleBinaryLoggerPerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {
    warmup(LoggerFactory.getLogger("perf-binary-vanilla-chronicle"));

    final int RUNS = 300000;
    final int THREADS = Runtime.getRuntime().availableProcessors();

    for (int size : new int[] { 64, 128, 256 }) {
        {//from w  ww . j  a  v a 2 s  . c o  m
            final long start = System.nanoTime();

            ExecutorService es = Executors.newFixedThreadPool(THREADS);
            for (int t = 0; t < THREADS; t++) {
                es.submit(new RunnableLogger(RUNS, size, "perf-binary-vanilla-chronicle"));
            }

            es.shutdown();
            es.awaitTermination(2, TimeUnit.MINUTES);

            final long time = System.nanoTime() - start;

            System.out.printf(
                    "ChronicleLog.MT (runs=%d, min size=%03d, elapsed=%.3f ms) took an average of %.3f us per entry\n",
                    RUNS, size, time / 1e6, time / 1e3 / (RUNS * THREADS));
        }
    }

    ChronicleTools.deleteOnExit(basePath("perf-binary-vanilla-chronicle"));
}

From source file:com.espertech.esper.multithread.TestMTStmtNamedWindowMerge.java

private void trySend(int numThreads, int numEventsPerThread) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.addEventType("SupportBean", SupportBean.class);
    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();//from ww  w  .ja  va 2s.c  o  m

    // setup statements
    engine.getEPAdministrator().createEPL("create window MyWindow.win:keepall() as select * from SupportBean");
    engine.getEPAdministrator()
            .createEPL("on SupportBean sb " + "merge MyWindow nw where nw.theString = sb.theString "
                    + " when not matched then insert select * "
                    + " when matched then update set intPrimitive = nw.intPrimitive + 1");

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future<Boolean> future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(new StmtNamedWindowMergeCallable(engine, numEventsPerThread));
    }

    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);

    // total up result
    for (int i = 0; i < numThreads; i++) {
        Boolean result = future[i].get();
        assertTrue(result);
    }

    // compare
    EventBean[] rows = engine.getEPRuntime().executeQuery("select * from MyWindow").getArray();
    assertEquals(numEventsPerThread, rows.length);
    for (EventBean row : rows) {
        assertEquals(numThreads - 1, row.get("intPrimitive"));
    }
    //long deltaTime = endTime - startTime;
    //System.out.println("Totals updated: " + totalUpdates + "  Delta cumu: " + deltaCumulative + "  Delta pooled: " + deltaTime);
}

From source file:jenkins.plugins.elanceodesk.workplace.notifier.HttpWorkerTest.java

@Test
public void testMutipleTriesWorker() throws InterruptedException {
    ExecutorService executorService = Executors.newCachedThreadPool();
    HttpWorker worker = new HttpWorker("http://localhost:8000/retry-test", "test1body", 30000, retries,
            Mockito.mock(PrintStream.class));
    executorService.submit(worker);//from   ww w  . j  a v a  2  s.co m
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.SECONDS);
    Assert.assertTrue(MyHandler.getRetryTestResult());
}

From source file:com.espertech.esper.multithread.TestMTDeterminismListener.java

private void trySend(int numThreads, int numEvents, boolean isPreserveOrder,
        ConfigurationEngineDefaults.Threading.Locking locking) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getThreading().setListenerDispatchPreserveOrder(isPreserveOrder);
    config.getEngineDefaults().getThreading().setListenerDispatchLocking(locking);

    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();/*from   w  ww.  ja v  a 2 s.c o  m*/

    // setup statements
    EPStatement stmtInsert = engine.getEPAdministrator()
            .createEPL("select count(*) as cnt from " + SupportBean.class.getName());
    SupportMTUpdateListener listener = new SupportMTUpdateListener();
    stmtInsert.addListener(listener);

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(new SendEventCallable(i, engine, new GeneratorIterator(numEvents)));
    }

    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);

    for (int i = 0; i < numThreads; i++) {
        assertTrue((Boolean) future[i].get());
    }

    EventBean events[] = listener.getNewDataListFlattened();
    long[] result = new long[events.length];
    for (int i = 0; i < events.length; i++) {
        result[i] = (Long) events[i].get("cnt");
    }
    //log.info(".trySend result=" + Arrays.toString(result));

    // assert result
    assertEquals(numEvents * numThreads, events.length);
    for (int i = 0; i < numEvents * numThreads; i++) {
        assertEquals(result[i], (long) i + 1);
    }
}

From source file:org.rhq.metrics.simulator.Simulator.java

private void shutdown(ExecutorService service, String serviceName, int wait) {
    log.info("Shutting down " + serviceName);
    service.shutdown();/*from w  w w .j  a v  a  2  s.com*/
    try {
        service.awaitTermination(wait, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }
    if (!service.isTerminated()) {
        log.info("Forcing " + serviceName + " shutdown.");
        service.shutdownNow();
    }
    log.info(serviceName + " shut down complete");
}

From source file:com.sangupta.httptools.DownloadUrlCommand.java

/**
 * Terminate the thread pool//from w  w w  .j a v  a2 s. c  om
 * 
 * @param pool
 *            the thread pool to terminate
 */
private void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(1, TimeUnit.DAYS)) {
            pool.shutdownNow(); // Cancel currently executing tasks

            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(60, TimeUnit.SECONDS))
                System.err.println("Pool did not terminate");
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }
}

From source file:org.mitre.mpf.mst.TestSystemStress3.java

/**
 * This test intentionally runs one file per job
 *//*from   w w w .j a  v  a 2 s  . c  o m*/
@Test(timeout = 180 * MINUTES)
public void runFaceOcvDetectImageManyJobs() throws Exception {
    testCtr++;
    log.info("Beginning test #{} runFaceOcvDetectImageManyJobs()", testCtr);
    IOFileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.fileFileFilter(),
            FileFilterUtils.suffixFileFilter(".jpg"));

    int numExtractors = 6; // number of extractors on Jenkins (* number of nodes, now 1)
    //        int numExtractors = 2;  // number of extractors on local VM * 1 node

    // for testing on local VM only
    //        Collection<File> files = FileUtils.listFiles(new File(getClass().getClassLoader().getResource("samples/face").getFile()),
    //            fileFilter, null);

    // for testing on Jenkins
    // 10,000 jpgs
    Collection<File> files = FileUtils.listFiles(new File("/mpfdata/datasets/mugshots_10000"), fileFilter,
            null);

    BlockingQueue<File> fQueue = new ArrayBlockingQueue<File>(files.size());
    for (File file : files) {
        fQueue.put(file);
    }
    ExecutorService executor = Executors.newFixedThreadPool(numExtractors);
    JobRunner[] jobRunners = new JobRunner[numExtractors];
    for (int i = 0; i < numExtractors; i++) {
        jobRunners[i] = new JobRunner(fQueue);
        executor.submit(jobRunners[i]);
    }
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

    Assert.assertEquals(
            "Number of files to process={} doesn't match actual number of jobs run={} (one job/file)",
            files.size(), manyJobsNumFilesProcessed);
    log.info("Successfully ran {} jobs for {} files, one file per job, without a hiccup",
            manyJobsNumFilesProcessed, files.size());
    log.info("Finished test runFaceOcvDetectImageManyJobs()");
}

From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java

@Test
public void testNewSingleThreadExecutorShutdownClean() throws InterruptedException {
    NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME);
    ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
    Assert.assertFalse(executor.isShutdown());
    Assert.assertFalse(executor.isTerminated());

    executor.execute(new NullRunnable());

    executor.shutdown();/*from w w  w. j ava2s. c o  m*/
    Assert.assertTrue(executor.isShutdown());
    executor.awaitTermination(10, TimeUnit.MILLISECONDS);
    Assert.assertTrue(executor.isTerminated());
}

From source file:com.espertech.esper.multithread.TestMTStmtNamedWindowSubqueryLookup.java

private void trySend(int numThreads, int numEventsPerThread) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getEventMeta()
            .setDefaultEventRepresentation(Configuration.EventRepresentation.MAP); // use Map-type events for testing
    config.addEventType("SupportBean", SupportBean.class);
    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();/*from  w  w w.j a v  a2  s  .co m*/

    // setup statements
    engine.getEPAdministrator().createEPL("create schema MyUpdateEvent as (key string, intupd int)");
    engine.getEPAdministrator().createEPL("create schema MySchema as (theString string, intval int)");
    EPStatement namedWindow = engine.getEPAdministrator()
            .createEPL("create window MyWindow.win:keepall() as MySchema");
    engine.getEPAdministrator()
            .createEPL("on MyUpdateEvent mue merge MyWindow mw " + "where mw.theString = mue.key "
                    + "when not matched then insert select key as theString, intupd as intval "
                    + "when matched then delete");
    EPStatement targetStatement = engine.getEPAdministrator().createEPL(
            "select (select intval from MyWindow mw where mw.theString = sb.theString) as val from SupportBean sb");

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future<Boolean> future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(
                new StmtNamedWindowSubqueryLookupCallable(i, engine, numEventsPerThread, targetStatement));
    }

    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);

    // total up result
    for (int i = 0; i < numThreads; i++) {
        Boolean result = future[i].get();
        assertTrue(result);
    }

    EventBean[] events = EPAssertionUtil.iteratorToArray(namedWindow.iterator());
    assertEquals(0, events.length);
}

From source file:org.apache.streams.facebook.provider.FacebookFriendFeedProvider.java

void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {/*from   w  w w . j ava2s . com*/
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
                System.err.println("Pool did not terminate");
            }
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }
}