Example usage for java.util.concurrent CountDownLatch getCount

List of usage examples for java.util.concurrent CountDownLatch getCount

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch getCount.

Prototype

public long getCount() 

Source Link

Document

Returns the current count.

Usage

From source file:org.apache.cxf.systest.jaxrs.AbstractJAXRSContinuationsTest.java

protected void doTestContinuation(String pathSegment) throws Exception {
    final String port = getPort();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);
    List<BookWorker> workers = new ArrayList<>(5);
    for (int x = 1; x < 6; x++) {
        workers.add(new BookWorker("http://localhost:" + port + getBaseAddress() + pathSegment + "/" + x,
                Integer.toString(x), "CXF in Action" + x, startSignal, doneSignal));
    }//from  w  w  w .j av a 2 s  .c  o m
    for (BookWorker w : workers) {
        executor.execute(w);
    }

    startSignal.countDown();
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
    for (BookWorker w : workers) {
        w.checkError();
    }
}

From source file:org.apache.directory.shared.client.api.LightweightLdapConnectionPoolTest.java

/**
 * Test the creation of many connections, not using a pool.
 * This test is very dependent on the TIME_WAIT duration, which can
 * be set by changing the net.inet.tcp.msl parameter :
 * <pre>//from  w  ww .j  a v  a  2s  .co  m
 * on Mac OSX :
 * $ sudo sysctl -w net.inet.tcp.msl=500
 * on LINUX :
 * $ sudo echo "1" > /proc/sys/net/ipv4/tcp_fin_timeout
 * </pre>
 * Note that this parameter is *not* to be made permanent. There is no
 * reason for creating ten of thousands of client connections, except for
 * a benchmark.
 */
@Test
@Ignore
public void testManyConnectionsNoPool() throws Exception {
    for (int j = 0; j < 1; j++) {
        System.out.println("-------------------");
        System.out.println("Iteration " + j);
        int nbIterations = 20000;
        int nbThreads = 1;
        CountDownLatch counter = new CountDownLatch(nbIterations * nbThreads);

        long t0 = System.currentTimeMillis();

        for (int i = 0; i < nbThreads; i++) {
            ConnectionThreadNoPool thread = new ConnectionThreadNoPool(nbIterations, counter);

            thread.start();
        }

        boolean result = counter.await(3000, TimeUnit.SECONDS);

        assertEquals(0, counter.getCount());

        long t1 = System.currentTimeMillis();

        System.out.println("Time to create and use " + nbIterations + " connections with " + nbThreads
                + "  threads = " + (t1 - t0));
    }
}

From source file:org.commonjava.maven.galley.TransferManagerImpl.java

private <T extends TransferBatch> T doBatch(final Set<Resource> resources, final T batch,
        final boolean suppressFailures) throws TransferException {
    logger.info("Attempting to batch-retrieve {} resources:\n  {}", resources.size(),
            new JoinString("\n  ", resources));

    final Set<BatchRetriever> retrievers = new HashSet<BatchRetriever>(resources.size());
    for (final Resource resource : resources) {
        retrievers.add(new BatchRetriever(this, resource, suppressFailures));
    }//from   ww w . jav  a2  s.  c om

    final Map<ConcreteResource, TransferException> errors = new HashMap<ConcreteResource, TransferException>();
    final Map<ConcreteResource, Transfer> transfers = new HashMap<ConcreteResource, Transfer>();

    int tries = 1;
    while (!retrievers.isEmpty()) {
        logger.debug("Starting attempt #{} to retrieve batch (batch size is currently: {})", tries,
                retrievers.size());
        final CountDownLatch latch = new CountDownLatch(resources.size());
        for (final BatchRetriever retriever : retrievers) {
            retriever.setLatch(latch);
            executor.execute(retriever);
        }

        while (latch.getCount() > 0) {
            try {
                latch.await(2, TimeUnit.SECONDS);

                if (latch.getCount() > 0) {
                    logger.info("Waiting for {} more transfers in batch to complete.", latch.getCount());
                    for (final BatchRetriever retriever : retrievers) {
                        logger.info("Batch waiting on {}", retriever.getLastTry());
                    }
                }
            } catch (final InterruptedException e) {
                logger.error(String.format("Failed to wait for batch retrieval attempts to complete: %s",
                        e.getMessage()), e);
                break;
            }
        }

        for (final BatchRetriever retriever : new HashSet<BatchRetriever>(retrievers)) {
            final ConcreteResource resource = retriever.getLastTry();
            final TransferException error = retriever.getError();
            if (error != null) {
                errors.put(resource, error);
                retrievers.remove(retriever);
                logger.warn("ERROR: {}...{}", error, resource, error.getMessage());
                continue;
            }

            final Transfer transfer = retriever.getTransfer();
            if (transfer != null && transfer.exists()) {
                transfers.put(resource, transfer);
                retrievers.remove(retriever);
                logger.debug("Completed: {}", resource);
                continue;
            }

            if (!retriever.hasMoreTries()) {
                logger.debug("Not completed, but out of tries: {}", resource);
                retrievers.remove(retriever);
            }
        }

        tries++;
    }

    batch.setErrors(errors);
    batch.setTransfers(transfers);

    return batch;
}

From source file:com.uber.hoodie.common.util.queue.BoundedInMemoryExecutor.java

/**
 * Start all Producers/* ww  w . j  a  v a2s.co m*/
 */
public ExecutorCompletionService<Boolean> startProducers() {
    // Latch to control when and which producer thread will close the queue
    final CountDownLatch latch = new CountDownLatch(producers.size());
    final ExecutorCompletionService<Boolean> completionService = new ExecutorCompletionService<Boolean>(
            executorService);
    producers.stream().map(producer -> {
        return completionService.submit(() -> {
            try {
                preExecute();
                producer.produce(queue);
            } catch (Exception e) {
                logger.error("error consuming records", e);
                queue.markAsFailed(e);
                throw e;
            } finally {
                synchronized (latch) {
                    latch.countDown();
                    if (latch.getCount() == 0) {
                        // Mark production as done so that consumer will be able to exit
                        queue.close();
                    }
                }
            }
            return true;
        });
    }).collect(Collectors.toList());
    return completionService;
}

From source file:org.artifactory.support.core.bundle.AbstractSupportBundleService.java

/**
 * Invoked post {@link @CollectService}//from ww  w  . j  a v a2 s  .c  om
 *
 * @param progress
 */
private void postProcess(CountDownLatch progress) {
    synchronized (progress) {
        progress.countDown();
        if (progress.getCount() > 0) {
            getLog().debug(Thread.currentThread().getName() + " has finished, "
                    + "still left '{}' tasks to break the latch", progress.getCount());
        } else {
            getLog().debug(Thread.currentThread().getName() + " has finished, all tasks are done!");
        }
    }
}

From source file:com.ottogroup.bi.streaming.runtime.StreamingAppRuntimeTest.java

/**
 * Test case for {@link StreamingAppRuntime#run(String[], OutputStream, Class)} being provided
 * a reference towards a configuration file holding a valid settings
 *//*from   w w  w  . jav  a  2  s.  com*/
@Test
public void testRun_withValidConfigurationFile() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    StringBuffer buf = new StringBuffer();
    buf.append("Invalid configuration at: str, error: must match \"test*.\"\n");
    OutputStream stream = Mockito.mock(OutputStream.class);
    DummyLogProcessingRuntime runtime = new DummyLogProcessingRuntime(latch);
    runtime.run(new String[] { "-f", "src/test/resources/valid-test-configuration.cfg" }, stream,
            DummyLogProcessingConfiguration.class);
    Mockito.verify(stream, Mockito.never()).write(Mockito.any());
    Assert.assertEquals(0, latch.getCount());
    Assert.assertNotNull(runtime.getExecutionEnvironment());
    Assert.assertEquals("test-application", runtime.getApplicationName());
    Assert.assertEquals("test application", runtime.getDescription());
}

From source file:com.bj58.spat.gaea.server.util.async.AsyncWorker.java

private void execTimeoutTask() {
    try {/*from  www.  j  a v  a 2  s .  c  o  m*/
        final AsyncTask task = taskQueue.take();
        if (task != null) {
            if ((System.currentTimeMillis() - task.getAddTime()) > task.getQtimeout()) {
                task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                return;
            } else {
                final CountDownLatch cdl = new CountDownLatch(1);
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Object obj = task.getHandler().run();
                            task.getHandler().messageReceived(obj);
                        } catch (Throwable ex) {
                            task.getHandler().exceptionCaught(ex);
                        } finally {
                            cdl.countDown();
                        }
                    }
                });
                cdl.await(getTimeout(task.getTimeout(), taskQueue.size()), TimeUnit.MILLISECONDS);
                if (cdl.getCount() > 0) {
                    task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                }
            }
        } else {
            logger.error("execTimeoutTask take task is null");
        }
    } catch (InterruptedException ie) {
        logger.error("");
    } catch (Throwable e) {
        logger.error("get task from poll error", e);
    }
}

From source file:org.onlab.util.BlockingBooleanTest.java

@Test
public void someWait() {
    BlockingBoolean b = new BlockingBoolean(false);

    int numThreads = 4;
    CountDownLatch sameLatch = new CountDownLatch(numThreads / 2);
    CountDownLatch waitLatch = new CountDownLatch(numThreads / 2);

    ExecutorService exec = Executors.newFixedThreadPool(numThreads);
    for (int i = 0; i < numThreads; i++) {
        final boolean value = (i % 2 == 1);
        exec.submit(() -> {//from   w w  w  .j ava 2  s  .  c om
            try {
                b.await(value);
                if (value) {
                    waitLatch.countDown();
                } else {
                    sameLatch.countDown();
                }
            } catch (InterruptedException e) {
                fail();
            }
        });
    }
    try {
        assertTrue(sameLatch.await(TIMEOUT, TimeUnit.MILLISECONDS));
        assertEquals(waitLatch.getCount(), numThreads / 2);
    } catch (InterruptedException e) {
        fail();
    }
    b.set(true);
    try {
        assertTrue(waitLatch.await(TIMEOUT, TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        fail();
    }
    exec.shutdown();
}

From source file:com.turo.pushy.apns.ApnsClientBenchmark.java

@Benchmark
@BenchmarkMode(Mode.SingleShotTime)//from w  w w.  j  ava  2 s. c  o  m
@Threads(1)
@Measurement(iterations = 20, batchSize = 1)
@Warmup(iterations = 20, batchSize = 1)
public long testSendNotifications() throws InterruptedException {
    final CountDownLatch countDownLatch = new CountDownLatch(this.pushNotifications.size());

    for (final SimpleApnsPushNotification notification : this.pushNotifications) {
        this.client.sendNotification(notification).addListener(
                new GenericFutureListener<Future<PushNotificationResponse<SimpleApnsPushNotification>>>() {

                    @Override
                    public void operationComplete(
                            final Future<PushNotificationResponse<SimpleApnsPushNotification>> future) {
                        if (future.isSuccess()) {
                            countDownLatch.countDown();
                        }
                    }
                });
    }

    countDownLatch.await();
    return countDownLatch.getCount();
}

From source file:org.apache.activemq.store.jdbc.JDBCCleanupLimitedPoolTest.java

@Test
public void testNoDeadlockOnXaPoolExhaustion() throws Exception {
    final CountDownLatch done = new CountDownLatch(1);
    final CountDownLatch doneCommit = new CountDownLatch(1000);

    final ActiveMQXAConnectionFactory factory = new ActiveMQXAConnectionFactory(
            broker.getTransportConnectorByScheme("tcp").getPublishableConnectString());

    ExecutorService executorService = Executors.newCachedThreadPool();
    // some contention over pool of 2
    for (int i = 0; i < 3; i++) {
        executorService.execute(new Runnable() {
            @Override//from  ww  w .j  a va2s .c  om
            public void run() {
                try {
                    ActiveMQXAConnection conn = (ActiveMQXAConnection) factory.createXAConnection();
                    conn.start();
                    XASession sess = conn.createXASession();
                    while (done.getCount() > 0 && doneCommit.getCount() > 0) {
                        Xid xid = createXid();
                        sess.getXAResource().start(xid, XAResource.TMNOFLAGS);
                        MessageProducer producer = sess.createProducer(sess.createQueue("test"));
                        producer.send(sess.createTextMessage("test"));
                        sess.getXAResource().end(xid, XAResource.TMSUCCESS);
                        sess.getXAResource().prepare(xid);
                        sess.getXAResource().commit(xid, false);
                        doneCommit.countDown();
                    }

                    conn.close();

                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
            }
        });
    }

    executorService.execute(new Runnable() {
        @Override
        public void run() {
            try {
                while (!done.await(10, TimeUnit.MILLISECONDS) && doneCommit.getCount() > 0) {
                    jdbcPersistenceAdapter.cleanup();
                }
            } catch (Exception ignored) {
            }

        }
    });

    executorService.shutdown();
    boolean allComplete = executorService.awaitTermination(40, TimeUnit.SECONDS);
    done.countDown();
    assertTrue("all complete", allComplete);
    executorService.shutdownNow();

    assertTrue("xa tx done", doneCommit.await(10, TimeUnit.SECONDS));
}