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.comcast.cats.vision.concurrent.RemoteWorkerTest.java

public void example() throws InterruptedException {
    CatsEventDispatcher dispatcher = new CatsEventDispatcherImpl();

    Settop settop = new MockSettop() {
        private static final long serialVersionUID = 1L;

        public boolean pressKey(RemoteCommand command) {
            LOGGER.info("pressKey");
            return true;
        }/*from   www.ja  v  a 2  s . c  o  m*/
    };

    dispatcher.addListener(this, CatsEventType.REMOTE_RESPONSE);

    RemoteEvent evt = new RemoteEvent(ActionType.PRESS, RemoteCommand.GUIDE, "10", null);
    ExecutorService executor = Executors.newFixedThreadPool(5);

    executor.execute(new PressKeyWorker(settop, evt, dispatcher));
    executor.awaitTermination(5, TimeUnit.SECONDS);
}

From source file:eu.artofcoding.beetlejuice.spring.SpringContextHelper.java

private void waitForExecutors(List<ExecutorService> executorServices) {
    long shutdownDeadline = System.currentTimeMillis() + 1000;
    for (ExecutorService executorService : executorServices) {
        try {// w w w.j a  v  a  2 s.c  om
            if (!executorService.awaitTermination(shutdownDeadline - System.currentTimeMillis(),
                    TimeUnit.MILLISECONDS)) {
                logger.info(String.format("Executor service %s failed to terminate", executorService));
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.warn(String.format("Interrupted while shutting down executor service %s", executorService));
            throw new RuntimeException("Interrupted while shutting down", e);
        }
        if (System.currentTimeMillis() > shutdownDeadline) {
            logger.warn("Timed out before waiting for all executor services");
        }
    }
}

From source file:com.google.cloud.bigtable.hbase.ManyThreadDriver.java

private static void runTest(String projectId, String instanceId, final String tableName) throws Exception {
    Configuration configuration = new Configuration();
    configuration.set("hbase.client.connection.impl", "com.google.cloud.bigtable.hbase1_0.BigtableConnection");
    configuration.set("google.bigtable.project.id", projectId);
    configuration.set("google.bigtable.instance.id", instanceId);
    try (Connection connection = ConnectionFactory.createConnection(configuration)) {
        Admin admin = connection.getAdmin();

        HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
        descriptor.addFamily(new HColumnDescriptor("cf"));
        try {/*from ww w . ja  v  a  2  s . c o m*/
            admin.createTable(descriptor);
        } catch (IOException ignore) {
            // Soldier on, maybe the table already exists.
        }

        final byte[] value = Bytes.toBytes(RandomStringUtils
                .randomAlphanumeric(Integer.parseInt(System.getProperty("valueSize", "1024"))));

        int numThreads = Integer.parseInt(System.getProperty("numThreads", "1000"));
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        for (int i = 0; i < numThreads; i++) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    try {
                        final Table table = connection.getTable(TableName.valueOf(tableName));

                        while (true) {
                            // Workload: two reads and a write.
                            table.get(new Get(Bytes.toBytes(key())));
                            table.get(new Get(Bytes.toBytes(key())));
                            Put p = new Put(Bytes.toBytes(key()));
                            p.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col"), value);
                            table.put(p);
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            };
            executor.execute(r);
        }

        // TODO Make a parameter
        executor.awaitTermination(48, TimeUnit.HOURS);
    }
}

From source file:org.waarp.openr66.protocol.http.rest.test.HttpTestRestR66Client.java

public static void launchThreads() {
    // init thread model
    ExecutorService pool = Executors.newFixedThreadPool(NB);
    HttpTestRestR66Client[] clients = new HttpTestRestR66Client[NB];
    for (int i = 0; i < NB; i++) {
        clients[i] = new HttpTestRestR66Client();
    }/*from   w  w w .  j  a  v  a2s . com*/
    for (int i = 0; i < NB; i++) {
        pool.execute(clients[i]);
    }
    pool.shutdown();
    try {
        while (!pool.awaitTermination(100000, TimeUnit.SECONDS))
            ;
    } catch (InterruptedException e) {
    }
}

From source file:org.geowebcache.sqlite.SqlitlePerf.java

/**
 * Select the created tiles using a connection provide by the connection manager.
 *//*  w  w  w . j a v a2  s . c  om*/
private static void pooledSqlitle(File rootDirectory, File seedFile, long[][] tiles) throws Exception {
    // creating a new database by copying the seeded one
    File databaseFile = new File(rootDirectory, "pooled_perf_test.sqlite");
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(String.format("Start pooled select from file '%s'.", databaseFile));
    }
    FileUtils.copyFile(seedFile, databaseFile);
    // submitting the select tasks
    ExecutorService executor = Executors.newFixedThreadPool(WORKERS);
    SqliteConnectionManager connectionManager = new SqliteConnectionManager(10, 2000);
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < tiles.length; i++) {
        long[] tile = tiles[i];
        executor.submit((Runnable) () -> connectionManager.doWork(databaseFile, true, connection -> {
            getTile(connection, tile);
        }));
        if (i != 0 && i % 10000 == 0) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Submitted %d select tasks.", i));
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Submitted %d select tasks.", TILES));
    }
    // lets wait for the workers to finish
    executor.shutdown();
    executor.awaitTermination(5, TimeUnit.MINUTES);
    // computing some stats
    long endTime = System.currentTimeMillis();
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(String.format("Tiles pooled select time '%d'.", endTime - startTime));
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(String.format("Tiles pooled selected per second '%f'.",
                TILES / (float) (endTime - startTime) * 1000));
    }
    // clean everything
    connectionManager.reapAllConnections();
    connectionManager.stopPoolReaper();
    FileUtils.deleteQuietly(databaseFile);
}

From source file:com.ejisto.modules.executor.TaskManager.java

private void shutdownExecutorService(ExecutorService service) {
    try {//  w  ww .j  av a 2 s.  c  o m
        service.shutdown();
        if (!service.awaitTermination(5L, SECONDS)) {
            service.shutdownNow();
        }
    } catch (InterruptedException e) {
        service.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

From source file:gov.ca.cwds.cals.service.ComplaintsService.java

@SuppressWarnings("squid:S2142") //Logging and informing client instead of shutdown
private void shutdownExecutionService(ExecutorService executorService) {
    executorService.shutdown();// ww  w .j av  a2 s .c o m
    try {
        if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
            executorService.shutdownNow();
        }
    } catch (InterruptedException e) {
        String message = "Can't properly shutdown complaints execution pool";
        LOGGER.warn(message, e);
        throw new ServiceException(message, e);
    }
}

From source file:org.apache.hadoop.hbase.master.MasterMobCompactionThread.java

/**
 * Wait for thread finish.// w w  w . j a  va 2 s .co m
 * @param t the thread to wait
 * @param name the thread name.
 */
private void waitFor(ExecutorService t, String name) {
    boolean done = false;
    while (!done) {
        try {
            done = t.awaitTermination(60, TimeUnit.SECONDS);
            LOG.info("Waiting for " + name + " to finish...");
            if (!done) {
                t.shutdownNow();
            }
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted waiting for " + name + " to finish...");
        }
    }
}

From source file:com.janrain.backplane.config.BackplaneConfig.java

private void shutdownExecutor(String serviceName, ExecutorService executor) {
    try {/*from   w  ww  . ja  v a2s  .  c o m*/
        executor.shutdown();
        if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
            logger.info(serviceName + " background thread shutdown properly");
        } else {
            executor.shutdownNow();
            if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                logger.error(serviceName + " background thread did not terminate");
            }
        }
    } catch (InterruptedException e) {
        logger.error(serviceName + " termination threw an exception", e);
        executor.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

From source file:org.ops4j.orient.spring.tx.blueprints.OrientGraphTransactionTest.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. ja  v a 2s . c o  m*/
    executorService.shutdown();
    executorService.awaitTermination(1000, TimeUnit.SECONDS);
}