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.apache.ctakes.ytex.kernel.evaluator.CorpusKernelEvaluatorImpl.java

@Override
public void evaluateKernelOnCorpus(Map<Long, Node> instanceIDMap, int nMod, boolean evalTest)
        throws InterruptedException {
    ExecutorService svc = Executors.newFixedThreadPool(nMod);
    List<Callable<Object>> taskList = new ArrayList<Callable<Object>>(nMod);
    for (int nSlice = 1; nSlice <= nMod; nSlice++) {
        taskList.add(new SliceEvaluator(instanceIDMap, nMod, nSlice, evalTest));
    }/* www.jav a 2 s  .c  o m*/
    svc.invokeAll(taskList);
    svc.shutdown();
    svc.awaitTermination(60 * 4, TimeUnit.MINUTES);
}

From source file:org.openhab.binding.modbus.internal.SimultaneousReadWriteTestCase.java

/**
 * Testing how binding handles simultaneous read and writes coming in.
 *
 * Even though the server in this test is able to handle at most one client at a time the binding
 * queues requests.//  ww w.j  av  a 2  s . co  m
 *
 * Note higher artificialServerWait in constructor
 *
 * @throws Exception
 */
@Test
public void testSimultaneousReadWrite() throws Exception {
    binding = new ModbusBinding();
    binding.updated(addSlave(addSlave(newLongPollBindingConfig(), SLAVE_NAME, type, null, 0, READ_COUNT),
            SLAVE2_NAME, type, null, 0, READ_COUNT));
    configureItems(SLAVE_NAME);
    configureItems(SLAVE2_NAME);

    /*
     * - both slaves read twice -> 4 read requests
     * - followed by write (slave1) -> 1 write request
     * - both slaves read once -> 2 read requests.
     * - Finally three writes (slave2) -> 3 write requets
     */
    int expectedRequests = 10;
    ExecutorService pool = Executors.newFixedThreadPool(expectedRequests);
    binding.execute();
    pool.execute(new UpdateThread(binding));
    pool.execute(new WriteCommandThread(binding, SLAVE_NAME, command));
    pool.execute(new UpdateThread(binding));
    pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
    pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
    pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));

    pool.shutdown();
    pool.awaitTermination(artificialServerWait * 7 + 5000, TimeUnit.MILLISECONDS);
    waitForRequests(expectedRequests);

    ArrayList<ModbusRequest> values = modbustRequestCaptor.getAllReturnValues();
    System.err.println(values);
    int readCount = 0;
    int writeCount = 0;
    for (ModbusRequest request : values) {
        if (request instanceof ReadMultipleRegistersRequest) {
            readCount++;
        } else if (request instanceof WriteSingleRegisterRequest) {
            writeCount++;
        }
    }
    Assert.assertEquals(6, readCount);
    Assert.assertEquals(4, writeCount);
}

From source file:org.apache.flume.sink.hdfs.HDFSEventSink.java

@Override
public void stop() {
    // do not constrain close() calls with a timeout
    synchronized (sfWritersLock) {
        for (Entry<String, BucketWriter> entry : sfWriters.entrySet()) {
            LOG.info("Closing {}", entry.getKey());

            try {
                entry.getValue().close();
            } catch (Exception ex) {
                LOG.warn("Exception while closing " + entry.getKey() + ". " + "Exception follows.", ex);
                if (ex instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }//from  w w w .  jav a 2s .  com
            }
        }
    }

    // shut down all our thread pools
    ExecutorService toShutdown[] = { callTimeoutPool, timedRollerPool };
    for (ExecutorService execService : toShutdown) {
        execService.shutdown();
        try {
            while (execService.isTerminated() == false) {
                execService.awaitTermination(Math.max(defaultCallTimeout, callTimeout), TimeUnit.MILLISECONDS);
            }
        } catch (InterruptedException ex) {
            LOG.warn("shutdown interrupted on " + execService, ex);
        }
    }

    callTimeoutPool = null;
    timedRollerPool = null;

    synchronized (sfWritersLock) {
        sfWriters.clear();
        sfWriters = null;
    }
    sinkCounter.stop();
    super.stop();
}

From source file:com.linkedin.pinot.integration.tests.MetadataAndDictionaryAggregationPlanClusterIntegrationTest.java

private void createAndUploadSegments(List<File> avroFiles, String tableName, boolean createStarTreeIndex,
        List<String> rawIndexColumns, Schema pinotSchema) throws Exception {
    TestUtils.ensureDirectoriesExistAndEmpty(_segmentDir, _tarDir);

    ExecutorService executor = Executors.newCachedThreadPool();
    ClusterIntegrationTestUtils.buildSegmentsFromAvro(avroFiles, 0, _segmentDir, _tarDir, tableName,
            createStarTreeIndex, rawIndexColumns, pinotSchema, executor);
    executor.shutdown();/*from ww  w  .  j av a 2  s  .  c  o m*/
    executor.awaitTermination(10, TimeUnit.MINUTES);

    uploadSegments(_tarDir);
}

From source file:com.vaushell.superpipes.tools.http.ImageExtractor.java

/**
 * Return the biggest image URI of this webpage.
 *
 * @param rootURI Webpage URI/*from   w w  w .j a va  2s  .  com*/
 * @return Biggest image
 * @throws IOException
 */
public BufferedImage extractBiggest(final URI rootURI) throws IOException {
    final List<URI> imagesURIs = new ArrayList<>();
    HttpEntity responseEntity = null;
    try {
        // Exec request
        final HttpGet get = new HttpGet(rootURI);

        try (final CloseableHttpResponse response = client.execute(get)) {
            final StatusLine sl = response.getStatusLine();
            if (sl.getStatusCode() != 200) {
                throw new IOException(sl.getReasonPhrase());
            }

            responseEntity = response.getEntity();

            try (final InputStream is = responseEntity.getContent()) {
                final Document doc = Jsoup.parse(is, "UTF-8", rootURI.toString());

                final Elements elts = doc.select("img");
                if (elts != null) {
                    for (final Element elt : elts) {
                        final String src = elt.attr("src");
                        if (src != null && !src.isEmpty()) {
                            try {
                                imagesURIs.add(rootURI.resolve(src));
                            } catch (final IllegalArgumentException ex) {
                                // Ignore wrong encoded URI
                            }
                        }
                    }
                }
            }
        }
    } finally {
        if (responseEntity != null) {
            EntityUtils.consume(responseEntity);
        }
    }

    final BufferedImage[] images = new BufferedImage[imagesURIs.size()];
    final ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < imagesURIs.size(); ++i) {
        final int num = i;

        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    images[num] = HTTPhelper.loadPicture(client, imagesURIs.get(num));
                } catch (final IOException ex) {
                    images[num] = null;
                }
            }
        });
    }

    service.shutdown();

    try {
        service.awaitTermination(1L, TimeUnit.DAYS);
    } catch (final InterruptedException ex) {
        // Ignore
    }

    BufferedImage biggest = null;
    int biggestSize = Integer.MIN_VALUE;
    for (int i = 0; i < imagesURIs.size(); ++i) {
        if (images[i] != null) {
            final int actualSize = images[i].getWidth() * images[i].getHeight();
            if (actualSize > biggestSize) {
                biggest = images[i];

                biggestSize = actualSize;
            }
        }
    }

    return biggest;
}

From source file:com.serotonin.bacnet4j.LocalDevice.java

public synchronized void terminate() {
    transport.terminate();//  ww w .  j  a  v  a2 s .  co  m
    initialized = false;

    if (ownsExecutorService) {
        ExecutorService temp = executorService;
        executorService = null;
        if (temp != null) {
            temp.shutdown();
            try {
                temp.awaitTermination(3, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                // no op
            }
        }
    }
}

From source file:com.addthis.hydra.task.source.DataSourceStreamList.java

void shutdownAndAwaitTermination(ExecutorService... pools) {
    for (ExecutorService pool : pools) {
        pool.shutdownNow(); // Disable new tasks from being submitted
        try {//w  ww.  j  av a2s.  co m
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(60, 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:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToPlainPipelineOutputs() throws InterruptedException, JSONException {
    firstStep = newPipelineWithResponseBody("{id:123}");

    // use a synchronized set to collect the pipeline output from multiple threads
    Set<JsonPipelineOutput> distinctOutputs = Collections.synchronizedSet(new HashSet<JsonPipelineOutput>());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    ExecutorService executorService = Executors.newCachedThreadPool();
    CountDownLatch countDown = new CountDownLatch(100);
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();/* w  w w  .  j a v  a2  s  . c o m*/
            distinctOutputs.add(firstStep.getOutput().toBlocking().single());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    // ensure all threads received the same JsonPipelineOutput instance with the expected JSON output
    assertEquals(1, distinctOutputs.size());
    JSONAssert.assertEquals("{id: 123}", firstStep.getStringOutput().toBlocking().first(),
            JSONCompareMode.STRICT);
}

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

private void tryChainedCountSum(int numThreads, 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();/*from   w  ww .  ja  v a  2  s.c o  m*/

    // setup statements
    EPStatement stmtInsertOne = engine.getEPAdministrator()
            .createEPL("insert into MyStreamOne select count(*) as cnt from " + SupportBean.class.getName());
    EPStatement stmtInsertTwo = engine.getEPAdministrator()
            .createEPL("insert into MyStreamTwo select sum(cnt) as mysum from MyStreamOne");
    EPStatement stmtInsertThree = engine.getEPAdministrator().createEPL("select * from MyStreamTwo");
    SupportUpdateListener listener = new SupportUpdateListener();
    stmtInsertThree.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();
    for (int i = 0; i < numEvents - 1; i++) {
        long expected = total(i + 1);
        assertEquals(expected, newEvents[i].get("mysum"));
    }

    stmtInsertOne.destroy();
    stmtInsertTwo.destroy();
    stmtInsertThree.destroy();
}