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:org.ops4j.orient.spring.tx.document.DocumentDatabaseTransactionTest.java

@Test
public void commitMultiThreaded() throws InterruptedException {

    ExecutorService executorService = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 5; i++) {
        executorService.submit(new CommitTask());
    }/*from  w  ww .j  av a  2 s  .  c o  m*/
    executorService.shutdown();
    executorService.awaitTermination(1000, TimeUnit.SECONDS);

}

From source file:io.udvi.amqp.mq.transport.session.CAMQPSessionManager.java

private void shutdownThreadPool(ExecutorService threadPool) {
    threadPool.shutdown();//from w w  w.j a v  a 2  s  . c  om
    try {
        threadPool.awaitTermination(300, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:com.quixey.hadoop.fs.oss.MultiPartUploader.java

private void awaitTermination(ExecutorService pool) {
    while (!pool.isTerminated()) {
        try {//from   w  ww.java  2  s.c o m
            pool.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.janrain.backplane.server.config.Backplane1Config.java

@PreDestroy
private void cleanup() {
    for (ExecutorService executor : backgroundServices) {
        try {
            executor.shutdown();/*from  www . j ava  2s.  co m*/
            if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
                logger.info("Background thread shutdown properly");
            } else {
                executor.shutdownNow();
                if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    logger.error("Background thread did not terminate");
                }
            }
        } catch (InterruptedException e) {
            logger.error("error shutting down background service", e);
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

From source file:org.nebula.framework.core.NodeWorker.java

private void shutdownExecutor(ExecutorService executor) {
    if (executor != null) {
        executor.shutdown();//from   www. j  a  v  a 2s .c  o m
        try {
            executor.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            //ignore the exception
        }
    }
}

From source file:org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.java

/**
 * Wait for the executor to terminate, according to the value of the
 * {@link #setAwaitTerminationSeconds "awaitTerminationSeconds"} property.
 *///from  w  ww .j  a v  a 2s .  c om
private void awaitTerminationIfNecessary(ExecutorService executor) {
    if (this.awaitTerminationSeconds > 0) {
        try {
            if (!executor.awaitTermination(this.awaitTerminationSeconds, TimeUnit.SECONDS)) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Timed out while waiting for executor"
                            + (this.beanName != null ? " '" + this.beanName + "'" : "") + " to terminate");
                }
            }
        } catch (InterruptedException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Interrupted while waiting for executor"
                        + (this.beanName != null ? " '" + this.beanName + "'" : "") + " to terminate");
            }
            Thread.currentThread().interrupt();
        }
    }
}

From source file:org.apache.hama.bsp.sync.TestSyncServiceFactory.java

@Test
public void testZKSyncStore() throws Exception {
    Configuration conf = new Configuration();
    int zkPort = BSPNetUtils.getFreePort(21811);
    conf.set("bsp.local.dir", "/tmp/hama-test");
    conf.set("bsp.output.dir", "/tmp/hama-test_out");
    conf.setInt(Constants.PEER_PORT, zkPort);
    conf.set(Constants.ZOOKEEPER_QUORUM, "localhost");
    conf.setInt(Constants.ZOOKEEPER_CLIENT_PORT, zkPort);
    System.setProperty("user.dir", "/tmp");
    // given null, should return zookeeper
    final SyncServer syncServer = SyncServiceFactory.getSyncServer(conf);
    syncServer.init(conf);/* w  w  w.j  a v  a 2  s.  c  o  m*/
    assertTrue(syncServer instanceof ZooKeeperSyncServerImpl);

    ZKServerThread serverThread = new ZKServerThread(syncServer);
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    executorService.submit(serverThread);

    executorService.awaitTermination(10, TimeUnit.SECONDS);

    final PeerSyncClient syncClient = SyncServiceFactory.getPeerSyncClient(conf);
    assertTrue(syncClient instanceof ZooKeeperSyncClientImpl);
    BSPJobID jobId = new BSPJobID("abc", 1);
    TaskAttemptID taskId = new TaskAttemptID(new TaskID(jobId, 1), 1);
    syncClient.init(conf, jobId, taskId);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                syncServer.stopServer();

            } catch (Exception e) {
                // too late to log!
            }
        }
    });

    Thread.sleep(3000);

    IntWritable data = new IntWritable(5);

    syncClient.storeInformation(syncClient.constructKey(jobId, String.valueOf(1L), "test"), data, true, null);

    ListenerTest listenerTest = new ListenerTest();

    syncClient.registerListener(syncClient.constructKey(jobId, String.valueOf(1L), "test"),
            ZKSyncEventFactory.getValueChangeEvent(), listenerTest);

    IntWritable valueHolder = new IntWritable();
    boolean result = syncClient.getInformation(syncClient.constructKey(jobId, String.valueOf(1L), "test"),
            valueHolder);
    assertTrue(result);
    int intVal = valueHolder.get();
    assertTrue(intVal == data.get());

    data.set(6);
    syncClient.storeInformation(syncClient.constructKey(jobId, String.valueOf(1L), "test"), data, true, null);
    valueHolder = new IntWritable();
    result = syncClient.getInformation(syncClient.constructKey(jobId, String.valueOf(1L), "test"), valueHolder);

    assertTrue(result);
    intVal = valueHolder.get();
    assertTrue(intVal == data.get());

    Thread.sleep(5000);

    assertEquals(true, listenerTest.getValue().equals("Changed"));

    syncServer.stopServer();

}

From source file:net.openhft.chronicle.logger.VanillChronicleQueuePerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {

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

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

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

            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));
        }
    }
}

From source file:org.v2020.service.ie.VnaImport.java

private void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {//from   w  w w .j  a va 2 s.  co m
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(getShutdownTimeoutInSeconds(), TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(getShutdownTimeoutInSeconds(), TimeUnit.SECONDS))
                LOG.error("Thread pool did not terminate", pool);
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }
}

From source file:com.nts.alphamale.handler.ExecutorHandler.java

public void shutdownExecutor(ExecutorService executor, int awaitTermination) {
    if (null != executor && !executor.isShutdown()) {
        executor.shutdown();/*w w  w.  ja  v a 2s . com*/
        try {
            if (!executor.awaitTermination(awaitTermination, TimeUnit.SECONDS)) {
                executor.shutdownNow();
                if (!executor.awaitTermination(awaitTermination, TimeUnit.SECONDS)) {
                    log.error("Executor did not terminate");
                }
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}