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.log4j2.Log4j2VanillaChroniclePerfTest.java

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

    warmup(LoggerFactory.getLogger("perf-binary-vanilla-chronicle"));
    warmup(LoggerFactory.getLogger("perf-plain-vanilla"));

    final int RUNS = 250000; // ~10s
    final int THREADS = Runtime.getRuntime().availableProcessors();

    for (int size : new int[] { 64, 128, 256 }) {
        {/*from  w w w .  ja  va  2s. c om*/
            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));
        }

        {
            final long start = System.nanoTime();

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

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

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

            System.out.printf(
                    "Plain.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));
        }
    }

    IOTools.deleteDir(basePath("perf-binary-vanilla-chronicle"));
}

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

private void trySend(int numThreads, int numRepeats, int numStatements) throws Exception {
    // Create same statement X times
    EPStatement stmt[] = new EPStatement[numStatements];
    SupportMTUpdateListener listeners[] = new SupportMTUpdateListener[stmt.length];
    for (int i = 0; i < stmt.length; i++) {
        stmt[i] = engine.getEPAdministrator().createEPL(" select * " + " from "
                + SupportMarketDataBean.class.getName() + ".std:groupwin(symbol).stat:uni(price)");
        listeners[i] = new SupportMTUpdateListener();
        stmt[i].addListener(listeners[i]);
    }/*from   w w w.jav a  2 s  . c  o  m*/

    // Start send threads
    // Each threads sends each symbol with price = 0 to numRepeats
    long startTime = System.currentTimeMillis();
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        Callable callable = new StmtSharedViewCallable(numRepeats, engine, SYMBOLS);
        future[i] = threadPool.submit(callable);
    }

    // Shut down
    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
    for (int i = 0; i < numThreads; i++) {
        assertTrue((Boolean) future[i].get());
    }
    long endTime = System.currentTimeMillis();
    long delta = endTime - startTime;
    assertTrue("delta=" + delta + " not less then 5 sec", delta < 5000); // should take less then 5 seconds even for 100 statements as they need to share resources thread-safely

    // Assert results
    for (SupportMTUpdateListener listener : listeners) {
        assertEquals(numRepeats * numThreads * SYMBOLS.length, listener.getNewDataList().size());
        EventBean[] newDataLast = listener.getNewDataList().get(listener.getNewDataList().size() - 1);
        assertEquals(1, newDataLast.length);
        EventBean result = newDataLast[0];
        assertEquals(numRepeats * numThreads, ((Long) result.get("datapoints")).longValue());
        assertTrue(Arrays.asList(SYMBOLS).contains(result.get("symbol")));
        assertEquals(sumToN(numRepeats) * numThreads, result.get("total"));
        listener.reset();
    }

    for (int i = 0; i < stmt.length; i++) {
        stmt[i].stop();
    }
}

From source file:com.ras.updater.Downloader.java

/**
 * This method will check for updates on all {@link #m_fileProviders} and download anything with an update.
 * @return true if at least one file was updated or false if no files were updated
 *//* w ww.ja  v a 2s .  co m*/
public boolean update() {
    ArrayList<Future<Boolean>> results = new ArrayList<Future<Boolean>>();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (IFileProvider fileProvider : m_fileProviders) {
        FileUpdaterCallable task = new FileUpdaterCallable(fileProvider);
        results.add(es.submit(task));
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(m_downloadTimeout, m_downloadTimeUnit))
            es.shutdownNow();
    } catch (InterruptedException e) {
        m_statusCallback.handleError(e);
        es.shutdownNow();
        Thread.currentThread().interrupt();
    }

    //Loop through the results for update values
    for (Future<Boolean> result : results) {
        try {
            if (result.isDone() && result.get() != null && result.get())
                return true;
        } catch (InterruptedException e) {
            //This should never happen
            m_statusCallback.handleError(e);
        } catch (ExecutionException e) {
            m_statusCallback.handleError(e);
        }
    }

    return false;
}

From source file:com.baifendian.swordfish.execserver.runner.flow.FlowRunnerManager.java

/**
 *  executor service/*from   w w  w  .j ava  2s  .  com*/
 */
private void shutdownExecutorService(ExecutorService executorService, boolean shutdownNow) {
    if (!executorService.isShutdown()) {
        try {
            if (!shutdownNow) {
                executorService.shutdown();
            } else {
                executorService.shutdownNow();
            }

            executorService.awaitTermination(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:com.vmware.photon.controller.model.adapters.azure.stats.AzureStatsService.java

private void awaitTermination(ExecutorService executor) {
    try {/*from   w w w .ja  v a  2  s .c  om*/
        if (!executor.awaitTermination(EXECUTOR_SHUTDOWN_INTERVAL_MINUTES, TimeUnit.MINUTES)) {
            logWarning("Executor service can't be shutdown for Azure. Trying to shutdown now...");
            executor.shutdownNow();
        }
        logFine("Executor service shutdown for Azure");
    } catch (InterruptedException e) {
        logSevere(e);
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        logSevere(e);
    }
}

From source file:org.apache.usergrid.persistence.qakka.serialization.sharding.ShardCounterSerializationTest.java

@Test
public void testConcurrentOperation() {

    // create multiple threads, each will increment counter by some number

    Injector injector = getInjector();/*from  ww  w  .  j  a v  a2 s.  c  om*/
    ShardCounterSerialization scs = injector.getInstance(ShardCounterSerialization.class);
    String queueName = "stco_queue_" + RandomStringUtils.randomAlphanumeric(10);
    long shardId = 100L;

    int poolSize = 20;
    int numThreads = 20;
    int numCounts = 3000;
    ExecutorService execService = Executors.newFixedThreadPool(poolSize);

    for (int i = 0; i < numThreads; i++) {

        execService.submit(() -> {

            for (int j = 0; j < numCounts; j++) {
                scs.incrementCounter(queueName, Shard.Type.DEFAULT, shardId, 1);
            }

        });
    }

    execService.shutdown();

    try {
        while (!execService.awaitTermination(3, TimeUnit.SECONDS)) {
            System.out.println("Waiting... " + scs.getCounterValue(queueName, Shard.Type.DEFAULT, shardId));
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // test that counter is correct value

    Assert.assertEquals(numThreads * numCounts, scs.getCounterValue(queueName, Shard.Type.DEFAULT, shardId));
}

From source file:org.olegz.uuid.TimeBasedUUIDGeneratorTests.java

@Test
public void performanceTestAsynch() throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(100);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from   ww  w  .j a  v  a 2 s  . c  o  m
    for (int i = 0; i < 1000000; i++) {
        executor.execute(new Runnable() {
            public void run() {
                TimeBasedUUIDGenerator.generateId();
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS);
    stopWatch.stop();
    System.out.println("Generated 1000000 UUID (async) via TimeBasedUUIDGenerator.generateId(): in "
            + stopWatch.getTotalTimeSeconds() + " seconds");

    executor = Executors.newFixedThreadPool(100);
    stopWatch = new StopWatch();
    stopWatch.start();
    for (int i = 0; i < 1000000; i++) {
        executor.execute(new Runnable() {
            public void run() {
                UUID.randomUUID();
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS);
    stopWatch.stop();
    System.out.println("Generated 1000000 UUID (async) via UUID.randomUUID(): in "
            + stopWatch.getTotalTimeSeconds() + " seconds");
}

From source file:com.miz.mizuu.SearchForNetworkShares.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.simple_list);

    pbar = (ProgressBar) findViewById(R.id.progressBar);

    status = (TextView) findViewById(R.id.overviewMessage);

    list = (ListView) findViewById(R.id.listView1);
    adapter = new NetworkAdapter();
    list.setAdapter(adapter);/*from  w ww .  j a  v  a  2  s.  co  m*/
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            sendBroadcast(arg2);
        }
    });

    new Thread() {
        @Override
        public void run() {
            ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int dest = 0; dest < 255; dest++) {
                String host = "192.168.1." + dest;
                executor.execute(pingRunnable(host));
            }

            executor.shutdown();
            try {
                executor.awaitTermination(60 * 1000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException ignored) {
            }

            if (running)
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pbar.setVisibility(View.GONE);
                        status.setVisibility(View.GONE);
                    }
                });
        }
    }.start();
}

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

/**
 * Retrieve the created tiles using the file blobstore.
 *//*from   ww  w .j  av  a2  s.  c o m*/
private static void fileStore(File seedDirectory, long[][] tiles) throws Exception {
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(String.format("Start reading from directory'%s'.", seedDirectory));
    }
    // submitting the read tasks
    ExecutorService executor = Executors.newFixedThreadPool(WORKERS);
    long startTime = System.currentTimeMillis();
    // instantiate the file blobstore
    BlobStore fileBlobStore = new FileBlobStore(seedDirectory.getPath());
    for (int i = 0; i < tiles.length; i++) {
        long[] tile = tiles[i];
        executor.submit((Runnable) () -> {
            TileObject mbtile = TileObject.createQueryTileObject("layer", tile, "grid", "image/png", null);
            try {
                fileBlobStore.get(mbtile);
            } catch (Exception exception) {
                throw Utils.exception(exception, "Error retrieving tile '%s'.", mbtile);
            }
        });
        if (i != 0 && i % 10000 == 0) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Submitted %d read tasks.", i));
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Submitted %d read 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 file blobstore read time '%d'.", endTime - startTime));
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(String.format("Tiles file blobstore reads per second '%f'.",
                TILES / (float) (endTime - startTime) * 1000));
    }
}

From source file:org.bonej.wrapperPlugins.AnisotropyWrapper.java

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