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:com.googlecode.concurrentlinkedhashmap.MultiThreadedTest.java

private void handleTimout(ConcurrentLinkedHashMap<?, ?> cache, ExecutorService es, TimeoutException e) {
    for (StackTraceElement[] trace : Thread.getAllStackTraces().values()) {
        for (StackTraceElement element : trace) {
            info("\tat " + element);
        }/* www  .  jav  a 2 s .  c om*/
        if (trace.length > 0) {
            info("------");
        }
    }
    es.shutdownNow();
    try {
        es.awaitTermination(10, SECONDS);
    } catch (InterruptedException ex) {
        fail("", ex);
    }

    // Print the state of the cache
    debug("Cached Elements: %s", cache.toString());
    debug("Deque Forward:\n%s", ascendingToString(cache));
    debug("Deque Backward:\n%s", descendingToString(cache));

    // Print the recorded failures
    for (String failure : failures) {
        debug(failure);
    }
    fail("Spun forever", e);
}

From source file:org.orekit.time.UTCScaleTest.java

@Test
public void testMultithreading() {

    // generate reference offsets using a single thread
    RandomGenerator random = new Well1024a(6392073424l);
    List<AbsoluteDate> datesList = new ArrayList<AbsoluteDate>();
    List<Double> offsetsList = new ArrayList<Double>();
    AbsoluteDate reference = utc.getFirstKnownLeapSecond().shiftedBy(-Constants.JULIAN_YEAR);
    double testRange = utc.getLastKnownLeapSecond().durationFrom(reference) + Constants.JULIAN_YEAR;
    for (int i = 0; i < 10000; ++i) {
        AbsoluteDate randomDate = reference.shiftedBy(random.nextDouble() * testRange);
        datesList.add(randomDate);/*from  w  w  w  .j  av  a 2  s . com*/
        offsetsList.add(utc.offsetFromTAI(randomDate));
    }

    // check the offsets in multi-threaded mode
    ExecutorService executorService = Executors.newFixedThreadPool(100);

    for (int i = 0; i < datesList.size(); ++i) {
        final AbsoluteDate date = datesList.get(i);
        final double offset = offsetsList.get(i);
        executorService.execute(new Runnable() {
            public void run() {
                Assert.assertEquals(offset, utc.offsetFromTAI(date), 1.0e-12);
            }
        });
    }

    try {
        executorService.shutdown();
        executorService.awaitTermination(3, TimeUnit.SECONDS);
    } catch (InterruptedException ie) {
        Assert.fail(ie.getLocalizedMessage());
    }

}

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentTest.java

@Test(expected = ExecutionException.class)
public void testRetryOnConflictExpectError() throws InterruptedException, ExecutionException {
    final String index = "JresUpdateDocumentTest.testRetryOnConflictExpectError".toLowerCase();
    final String type = "test";
    final String id = "warzone";

    final AtomicReference<String> error = new AtomicReference<String>();
    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    List<Future<?>> futures = new ArrayList<Future<?>>(numThreads);
    for (int i = 0; i < numThreads; i++) {
        futures.add(x.submit(new Callable<Void>() {
            @Override/*  www.  j  ava  2s.  c  om*/
            public Void call() throws Exception {
                for (int j = 0; j < numIterations; j++) {
                    jres.quest(new JresUpdateDocument(index, type, id, ImmutableMap.of("value", 0)));
                }
                return null;
            }
        }));
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    for (Future<?> future : futures) {
        // expecting a conflict exception from ElasticSearch
        future.get();
    }
}

From source file:net.darkmist.clf.Main.java

private void handleFiles(String fileNames[], int off, int len) {
    DirTraverser traverser;//from  ww w  . jav a2s  .  c o  m
    Queue<File> files;
    ExecutorService executor;

    // convert fileNames to Files and put them in a Queue
    files = Util.newQueue(Util.getStringToFileConverter(), fileNames, off, len);
    //executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    executor = MoreExecutors.newCurrentThreadPool();

    traverser = new DirTraverser(files, new ExecutorFileHandler(executor, this));

    // let her rip
    traverser.run();

    // all done traversing... shutdown the executor
    executor.shutdown();
    // and wait for it
    while (!executor.isTerminated()) {
        try {
            executor.awaitTermination(STATUS_TIME, STATUS_UNIT);
        } catch (InterruptedException e) {
            logger.warn("Ignoring InterruptedException until thread pool executor stops", e);
        }
        if (logger.isDebugEnabled() && executor instanceof ThreadPoolExecutor) {
            ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
            logger.debug("ThreadPool size=" + pool.getPoolSize() + " active=" + pool.getActiveCount()
                    + " queue=" + pool.getQueue().size());
        }
    }
    executor = null;
    logger.debug("handleFiles done...");
}

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

private void trySendCountFollowedBy(int numThreads, int numEvents,
        ConfigurationEngineDefaults.Threading.Locking locking) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getThreading().setInsertIntoDispatchLocking(locking);
    config.getEngineDefaults().getThreading().setInsertIntoDispatchTimeout(5000); // 5 second timeout
    // This should fail all test in this class
    // config.getEngineDefaults().getThreading().setInsertIntoDispatchPreserveOrder(false);

    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();//from  w w  w  .j  a  va 2s.  c o m

    // setup statements
    EPStatement stmtInsert = engine.getEPAdministrator()
            .createEPL("insert into MyStream select count(*) as cnt from " + SupportBean.class.getName());
    stmtInsert.addListener(new UpdateListener() {

        public void update(EventBean[] newEvents, EventBean[] oldEvents) {
            log.debug(".update cnt=" + newEvents[0].get("cnt"));
        }
    });

    SupportUpdateListener listeners[] = new SupportUpdateListener[numEvents];
    for (int i = 0; i < numEvents; i++) {
        String text = "select * from pattern [MyStream(cnt=" + (i + 1) + ") -> MyStream(cnt=" + (i + 2) + ")]";
        EPStatement stmt = engine.getEPAdministrator().createEPL(text);
        listeners[i] = new SupportUpdateListener();
        stmt.addListener(listeners[i]);
    }

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    ReentrantReadWriteLock sharedStartLock = new ReentrantReadWriteLock();
    sharedStartLock.writeLock().lock();
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(
                new SendEventRWLockCallable(i, sharedStartLock, engine, new GeneratorIterator(numEvents)));
    }
    Thread.sleep(100);
    sharedStartLock.writeLock().unlock();

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

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

    // assert result
    for (int i = 0; i < numEvents - 1; i++) {
        assertEquals("Listener not invoked: #" + i, 1, listeners[i].getNewDataList().size());
    }
}

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

private void tryMultiInsertGroup(int numThreads, int numStatements, int numEvents) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    // This should fail all test in this class
    // config.getEngineDefaults().getThreading().setInsertIntoDispatchPreserveOrder(false);

    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();// w  w w  . j  a v a  2s.c  o m

    // setup statements
    EPStatement[] insertIntoStmts = new EPStatement[numStatements];
    for (int i = 0; i < numStatements; i++) {
        insertIntoStmts[i] = engine.getEPAdministrator().createEPL("insert into MyStream select " + i
                + " as ident,count(*) as cnt from " + SupportBean.class.getName());
    }
    EPStatement stmtInsertTwo = engine.getEPAdministrator()
            .createEPL("select ident, sum(cnt) as mysum from MyStream group by ident");
    SupportUpdateListener listener = new SupportUpdateListener();
    stmtInsertTwo.addListener(listener);

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    ReentrantReadWriteLock sharedStartLock = new ReentrantReadWriteLock();
    sharedStartLock.writeLock().lock();
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(
                new SendEventRWLockCallable(i, sharedStartLock, engine, new GeneratorIterator(numEvents)));
    }
    Thread.sleep(100);
    sharedStartLock.writeLock().unlock();

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

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

    // assert result
    EventBean newEvents[] = listener.getNewDataListFlattened();
    ArrayList resultsPerIdent[] = new ArrayList[numStatements];
    for (EventBean theEvent : newEvents) {
        int ident = (Integer) theEvent.get("ident");
        if (resultsPerIdent[ident] == null) {
            resultsPerIdent[ident] = new ArrayList();
        }
        long mysum = (Long) theEvent.get("mysum");
        resultsPerIdent[ident].add(mysum);
    }

    for (int statement = 0; statement < numStatements; statement++) {
        for (int i = 0; i < numEvents - 1; i++) {
            long expected = total(i + 1);
            assertEquals(expected, resultsPerIdent[statement].get(i));
        }
    }

    // destroy
    for (int i = 0; i < numStatements; i++) {
        insertIntoStmts[i].destroy();
    }
    stmtInsertTwo.destroy();
}

From source file:com.esri.cordova.geolocation.AdvancedGeolocation.java

/**
 * Shutdown cordova thread pool. This assumes we are in control of all tasks running
 * in the thread pool.//from  www.  ja va 2  s .c o m
 * Additional info: http://developer.android.com/reference/java/util/concurrent/ExecutorService.html
 * @param pool Cordova application's thread pool
 */
private void shutdownAndAwaitTermination(ExecutorService pool) {
    Log.d(TAG, "Attempting to shutdown cordova threadpool");
    if (!pool.isShutdown()) {
        try {
            // Disable new tasks from being submitted
            pool.shutdown();
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
                    System.err.println("Cordova thread pool did not terminate.");
                }
            }
        } catch (InterruptedException ie) {
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.npstrandberg.simplemq.MessageQueueImp.java

private void shutdownAndAwaitTermination(ExecutorService pool) {

    pool.shutdown(); // Disable new tasks from being submitted

    try {/*from  w ww . java 2s  . co m*/

        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks

            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(5, 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:hivemall.mix.server.MixServerTest.java

@Test
public void testMultipleClients() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "3" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);/*  w  w w  .ja  v  a 2s  . c o  m*/

    waitForState(server, ServerState.RUNNING);

    final int numClients = 5;
    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < numClients; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient("testMultipleClients", port);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(10, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}