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.iselect.kernal.geo.service.GeographicServiceImpl.java

@Override
public List<Future> importGeos(List<CountryDto> countries) {
    ExecutorService pools = Executors.newFixedThreadPool(2);
    List<Future> results = new ArrayList<>(countries.size());
    for (CountryDto country : countries) {
        Future result = pools.submit(new GeographicCallable(country));
        results.add(result);//  w ww  . j a va  2 s .  c  o m
    }
    try {
        pools.awaitTermination(1, TimeUnit.MINUTES);
        pools.shutdown();
    } catch (InterruptedException ex) {
        Logger.getLogger(GeographicServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return results;
}

From source file:com.polyvi.xface.extension.XExtensionManager.java

/**
 * /*from w w w. j  a va 2  s  . co  m*/
 */
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(THREAD_POOL_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(THREAD_POOL_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) {
                XLog.d(CLASS_NAME, "Thread 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:com.navercorp.pinpoint.collector.receiver.tcp.TCPReceiver.java

private void shutdownExecutor(ExecutorService executor) {
    if (executor == null) {
        return;//w w w.ja  v  a2 s . c om
    }
    executor.shutdown();
    try {
        executor.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:org.artifactory.descriptor.reader.CentralConfigReaderTest.java

public void readAllConfigFiles() throws Exception {
    Properties propTest = new Properties();
    propTest.setProperty(substituteRepoKeys.getPropertyName() + "3rdp-releases", "third-party-releases");
    propTest.setProperty(substituteRepoKeys.getPropertyName() + "3rdp-snapshots", "third-party-snapshots");
    propTest.setProperty(substituteRepoKeys.getPropertyName() + "3rd-party", "third-party");
    // load the repo key substitute
    Map<String, String> subs = (Map<String, String>) TestUtils.invokeStaticMethod(
            ArtifactorySystemProperties.class, "fillRepoKeySubstitute", new Class[] { Properties.class },
            new Object[] { propTest });
    assertEquals(subs.size(), 3);//from   ww w  .  ja va  2s . co m
    TestUtils.setField(getBound().getArtifactoryProperties(), "substituteRepoKeys", subs);
    File backupDirs = ResourceUtils.getResourceAsFile("/config");
    Collection<File> oldArtifactoryConfigs = FileUtils.listFiles(backupDirs, new String[] { "xml" }, true);
    assertTrue(oldArtifactoryConfigs.size() > 10, "Where are all my test files??");

    // run in parallel for better speed
    ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (File oldArtifactoryConfig : oldArtifactoryConfigs) {
        executorService.submit(new ConfigReadWriteTester(oldArtifactoryConfig));
    }
    executorService.shutdown();
    //executorService.awaitTermination(15, TimeUnit.SECONDS);
    executorService.awaitTermination(1500, TimeUnit.SECONDS);

    assertNull(failureMessage, failureMessage);
}

From source file:org.sipfoundry.sipxconfig.upload.DefaultSystemFirmwareInstall.java

public void installAvailableFirmwares() {
    List<DefaultSystemFirmware> firmwares = findAvailableFirmwares();
    if (null == firmwares || firmwares.isEmpty()) {
        return;/*from   w  w w.ja  v a  2  s. c  om*/
    }

    try {
        ExecutorService executorService = Executors.newFixedThreadPool(firmwares.size());
        for (DefaultSystemFirmware firmware : firmwares) {
            executorService.submit(new InstallAvailableFirmware(firmware));
        }
        executorService.shutdown();
        executorService.awaitTermination(300, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        LOG.error("Unexpected termination of firmware install", e);
    }
}

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

private void trySend(int numThreads, int numEventsPerThread, boolean indexShare) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.addEventType("SupportBean", SupportBean.class);
    config.addPlugInAggregationFunction("intListAgg", MyIntListAggregation.class.getName());
    config.getEngineDefaults().getEventMeta()
            .setDefaultEventRepresentation(Configuration.EventRepresentation.MAP); // use Map-type events for testing
    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();//from ww  w. ja v a 2s. c  om

    // setup statements
    engine.getEPAdministrator().createEPL("create schema UpdateEvent as (uekey string, ueint int)");
    engine.getEPAdministrator().createEPL("create schema WindowSchema as (wskey string, wsint int)");

    String createEpl = "create window MyWindow.win:keepall() as WindowSchema";
    if (indexShare) {
        createEpl = "@Hint('enable_window_subquery_indexshare') " + createEpl;
    }
    EPStatement namedWindow = engine.getEPAdministrator().createEPL(createEpl);

    engine.getEPAdministrator().createEPL("create index ABC on MyWindow(wskey)");
    engine.getEPAdministrator()
            .createEPL("on UpdateEvent mue merge MyWindow mw " + "where uekey = wskey and ueint = wsint "
                    + "when not matched then insert select uekey as wskey, ueint as wsint "
                    + "when matched then delete");
    // note: here all threads use the same string key to insert/delete and different values for the int
    EPStatement targetStatement = engine.getEPAdministrator().createEPL(
            "select (select intListAgg(wsint) from MyWindow mw where wskey = 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 StmtNamedWindowSubqueryAggCallable(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:it.infn.ct.futuregateway.apiserver.APIContextListener.java

@Override
public final void contextDestroyed(final ServletContextEvent sce) {
    ExecutorService exServ;
    try {/* ww  w  .  jav a 2 s .  c  o  m*/
        Context ctx = new InitialContext();
        exServ = (ExecutorService) ctx.lookup("java:comp/env/threads/Submitter");
    } catch (NamingException ex) {
        exServ = (ExecutorService) sce.getServletContext().getAttribute("SubmissionThreadPool");
    }
    exServ.shutdown();
    try {
        if (!exServ.awaitTermination(Constants.MAXTHREADWAIT, TimeUnit.MINUTES)) {
            log.warn("Failed to shutdown the submission thread pool.");
        }
    } catch (InterruptedException ex) {
        log.error(ex);
    }
}

From source file:net.openhft.chronicle.logger.log4j1.Log4j1IndexedChroniclePerfTest.java

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

    final int RUNS = 1000000;
    final int THREADS = 10;

    for (int size : new int[] { 64, 128, 256 }) {
        {/*from   w w w . ja  va2  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-indexed-chronicle"));
            }

            es.shutdown();
            es.awaitTermination(60, TimeUnit.SECONDS);

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

            es.shutdown();
            es.awaitTermination(60, TimeUnit.SECONDS);

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

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

From source file:net.openhft.chronicle.logger.log4j1.Log4j1VanillaChroniclePerfTest.java

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

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

    for (int size : new int[] { 64, 128, 256 }) {
        {/* w ww. ja  va 2s . com*/
            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(5, 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:net.openhft.chronicle.logger.logback.LogbackVanillaChroniclePerfTest.java

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

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

    for (int size : new int[] { 64, 128, 256 }) {
        {//from   w  w  w. jav  a  2s.c  om
            final int RUNS = 250000;
            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 int RUNS = 10000;
            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(5, 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"));
}