Example usage for java.util.concurrent CountDownLatch CountDownLatch

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

Introduction

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

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

From source file:com.alibaba.druid.benckmark.pool.Case_Concurrent_50.java

private void p0(final DataSource dataSource, String name) throws Exception {
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();

    final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
    for (int i = 0; i < THREAD_COUNT; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {

                    for (int i = 0; i < COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT 1");
                        Thread.sleep(0, 1000 * 100);
                        rs.close();// w  ww  .ja va2 s  .  co  m
                        stmt.close();
                        conn.close();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    endLatch.countDown();
                }
            }
        };
        thread.start();
    }
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println(name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc
            + " FGC " + fullGC);
}

From source file:fi.jumi.core.stdout.OutputCapturerTest.java

@Test
public void concurrent_captures_are_isolated_from_each_other() throws Exception {
    CountDownLatch barrier = new CountDownLatch(2);
    OutputListenerSpy listener1 = new OutputListenerSpy();
    OutputListenerSpy listener2 = new OutputListenerSpy();

    runConcurrently(() -> {//  w  w w.  j  a v a 2 s  .  com
        capturer.captureTo(listener1);
        sync(barrier);
        capturer.out().print("from thread 1");
    }, () -> {
        capturer.captureTo(listener2);
        sync(barrier);
        capturer.out().print("from thread 2");
    });

    assertThat(listener1.out).containsExactly("from thread 1");
    assertThat(listener2.out).containsExactly("from thread 2");
}

From source file:com.datatorrent.demos.dimensions.ads.HDHTApplicationTest.java

@Test
public void testApplication() throws Exception {
    LocalMode lma = LocalMode.newInstance();
    Configuration conf = new Configuration(false);
    conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "1");

    conf.set("dt.operator.QueryResult.prop.configProperties(metadata.broker.list)", "localhost:9092");

    conf.set("dt.operator.Store.fileStore.basePath", "target/HDSApplicationTestStore");

    conf.set("dt.operator.Query.brokerSet", "localhost:9092");
    conf.set("dt.operator.Query.topic", kafkaQueryTopic);
    conf.set("dt.operator.QueryResult.topic", kafkaQueryResultTopic);

    conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "2");
    conf.set("dt.operator.InputGenerator.numPublishers", "2");
    conf.set("dt.loggers.level", "server.*:INFO");

    lma.prepareDAG(new ApplicationWithHDHT(), conf);
    LocalMode.Controller lc = lma.getController();
    //lc.setHeartbeatMonitoringEnabled(false);
    lc.runAsync();/*w  w w .  jav  a2 s .c  o m*/

    //Write messages to kafkaQueryTopic
    KafkaTestProducer kafkaQuery = new KafkaTestProducer(kafkaQueryTopic);
    String testQuery = "{\n" + " \"id\": \"query1\",\n"
            + " \"dimensionSelector\": \"time=MINUTES:publisherId\",\n" + " \"keys\": {\n"
            + "  \"publisherId\": 1\n" + " }\n" + "}";

    List<String> testQueryMessages = new ArrayList<String>();
    testQueryMessages.add(testQuery);
    kafkaQuery.setMessages(testQueryMessages);
    kafkaQuery.run();

    // Setup a message listener to receive the query results
    CountDownLatch latch = new CountDownLatch(100);
    KafkaTestConsumer queryResultsListener = new KafkaTestConsumer(kafkaQueryResultTopic);
    queryResultsListener.setLatch(latch);
    new Thread(queryResultsListener).start();

    // Wait to receive messages
    latch.await(15, TimeUnit.SECONDS);
    lc.shutdown();

    // Evaluate results
    String lastMessage;
    LOG.info("Sent " + kafkaQuery.getSendCount() + " messages to " + kafkaQueryTopic);
    LOG.info("Received " + queryResultsListener.holdingBuffer.size() + " messages from Kafka on "
            + kafkaQueryResultTopic + " topic");
    Assert.assertTrue("Minimum messages received from Kafka " + queryResultsListener.holdingBuffer,
            queryResultsListener.holdingBuffer.size() >= 1);

    while (!queryResultsListener.holdingBuffer.isEmpty()) {
        lastMessage = queryResultsListener.getMessage(queryResultsListener.holdingBuffer.poll());
        Assert.assertNotNull("Did not receive message from Kafka", lastMessage);
        LOG.info("received:\n{}", lastMessage);
    }
}

From source file:com.kurento.kmf.jsonrpcconnector.client.JsonRpcClientWebSocket.java

private synchronized void connectIfNecessary() throws IOException {

    if (wsSession == null) {

        final CountDownLatch latch = new CountDownLatch(1);

        TextWebSocketHandler webSocketHandler = new TextWebSocketHandler() {

            @Override//from   w  ww .j a  va  2s  .co m
            public void afterConnectionEstablished(WebSocketSession wsSession2) throws Exception {

                wsSession = wsSession2;
                rs = new WebSocketResponseSender(wsSession);
                latch.countDown();
            }

            @Override
            public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
                handleWebSocketTextMessage(message);
            }

            @Override
            public void afterConnectionClosed(WebSocketSession s, CloseStatus status) throws Exception {

                // TODO Call this when you can't reconnect or close is
                // issued by client.
                handlerManager.afterConnectionClosed(session, status.getReason());
                log.debug("WebSocket closed due to: {}", status);
                wsSession = null;
                // TODO Start a timer to force reconnect in x millis
                // For the moment we are going to force it sending another
                // message.
            }
        };

        WebSocketConnectionManager connectionManager = new WebSocketConnectionManager(
                new StandardWebSocketClient(), webSocketHandler, url);

        connectionManager.setHeaders(headers);
        connectionManager.start();

        try {
            latch.await();

            if (session == null) {

                session = new ClientSession(null, null, JsonRpcClientWebSocket.this);
                handlerManager.afterConnectionEstablished(session);

            } else {

                String result = rsHelper.sendRequest(JsonRpcConstants.METHOD_RECONNECT, String.class);

                log.info("Reconnection result: {}", result);

            }

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.networknt.openapi.ValidatorHandlerTest.java

@Test
public void testInvalidRequstPath() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {// ww  w.j a v  a2s.c  om
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/api").setMethod(Methods.GET);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}

From source file:com.microsoft.office.integration.test.ContactsAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeContact();//  w w  w .  ja  v  a 2  s .  c  om
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getContacts().getAsync(contact.getId()), new FutureCallback<IContact>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(IContact result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }
            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:org.mule.module.http.functional.listener.HttpListenerWorkerThreadingProfileTestCase.java

private void assertMaxThreadsActive(String flowName, String url, int maxThreadsActive) throws Exception {
    maxActiveNumberOfRequestExecutedLatch = new CountDownLatch(maxThreadsActive);

    sendRequestUntilNoMoreWorkers(flowName, url, maxThreadsActive);
    // Due to differences in buffer sizes, the exception that is caused client side may be one of two different
    // exceptions.
    expectedException//from w  ww . ja v  a 2s.c  om
            .expect(anyOf(instanceOf(NoHttpResponseException.class), instanceOf(SocketException.class)));
    try {
        httpClientExecutor.execute(Request.Get(url));
    } finally {
        waitingLatch.release();
    }
}

From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java

@Test
public void testRebuildAgainstOtherProcesses() throws Exception {
    NodeCache cache = null;/*from w ww  . ja va  2s.  c  o m*/
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    client.start();
    try {
        client.create().forPath("/test");
        client.create().forPath("/test/snafu", "original".getBytes());

        final CountDownLatch latch = new CountDownLatch(1);
        cache = new NodeCache(client, "/test/snafu");
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                latch.countDown();
            }
        });
        cache.rebuildTestExchanger = new Exchanger<Object>();

        ExecutorService service = Executors.newSingleThreadExecutor();
        final NodeCache finalCache = cache;
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                // simulate another process updating the node while we're rebuilding
                client.setData().forPath("/test/snafu", "other".getBytes());

                ChildData currentData = finalCache.getCurrentData();
                Assert.assertNotNull(currentData);

                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                return null;
            }
        });
        cache.start(false);
        future.get();

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNotNull(cache.getCurrentData());
        Assert.assertEquals(cache.getCurrentData().getData(), "other".getBytes());
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:org.factor45.jhcb.benchmark.ApacheBenchmark.java

@Override
protected BatchResult runBatch() {
    final CountDownLatch latch = new CountDownLatch(this.threads);
    final Vector<ThreadResult> threadResults = new Vector<ThreadResult>(this.threads);

    long batchStart = System.nanoTime();
    for (int i = 0; i < this.threads; i++) {
        this.executor.submit(new Runnable() {

            @Override//from  ww w .j  a  v  a 2 s .  c om
            public void run() {
                int successful = 0;
                long start = System.nanoTime();
                for (int i = 0; i < requestsPerThreadPerBatch; i++) {
                    HttpGet get = new HttpGet(url);
                    try {
                        HttpResponse response = client.execute(get);
                        response.getEntity().consumeContent();
                        if (response.getStatusLine().getStatusCode() == 200) {
                            successful++;
                        }
                    } catch (IOException e) {
                        get.abort();
                    }
                }

                long totalTime = System.nanoTime() - start;
                threadResults.add(new ThreadResult(requestsPerThreadPerBatch, successful, totalTime));
                latch.countDown();
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        Thread.interrupted();
    }
    long batchTotalTime = System.nanoTime() - batchStart;

    return new BatchResult(threadResults, batchTotalTime);
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorCluster.java

@Test
public void testLostRestart() throws Exception {
    final Timing timing = new Timing();

    CuratorFramework client = null;//  ww w  .java2s  .  c  o  m
    TestingCluster cluster = new TestingCluster(3);
    cluster.start();
    try {
        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();
        client.sync("/", null);

        final AtomicReference<Exception> error = new AtomicReference<Exception>(null);
        final AtomicReference<String> lockNode = new AtomicReference<String>(null);
        final Semaphore semaphore = new Semaphore(0);
        final CountDownLatch lostLatch = new CountDownLatch(1);
        final CountDownLatch internalLostLatch = new CountDownLatch(1);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                try {
                    List<String> names = client.getChildren().forPath("/leader");
                    if (names.size() != 1) {
                        semaphore.release();
                        Exception exception = new Exception("Names size isn't 1: " + names.size());
                        error.set(exception);
                        return;
                    }
                    lockNode.set(names.get(0));

                    semaphore.release();
                    if (!timing.multiple(4).awaitLatch(internalLostLatch)) {
                        error.set(new Exception("internalLostLatch await failed"));
                    }
                } finally {
                    lostLatch.countDown();
                }
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    internalLostLatch.countDown();
                }
            }
        };
        LeaderSelector selector = new LeaderSelector(client, "/leader", listener);
        selector.start();
        Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
        if (error.get() != null) {
            throw new AssertionError(error.get());
        }

        Collection<InstanceSpec> instances = cluster.getInstances();
        cluster.stop();

        Assert.assertTrue(timing.multiple(4).awaitLatch(lostLatch));
        timing.sleepABit();
        Assert.assertFalse(selector.hasLeadership());

        Assert.assertNotNull(lockNode.get());

        cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()]));
        cluster.start();

        try {
            client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get())); // simulate the lock deleting due to session expiration
        } catch (Exception ignore) {
            // ignore
        }

        Assert.assertTrue(semaphore.availablePermits() == 0);
        Assert.assertFalse(selector.hasLeadership());

        selector.requeue();
        Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
    } finally {
        IOUtils.closeQuietly(client);
        IOUtils.closeQuietly(cluster);
    }
}