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.sixt.service.framework.kafka.KafkaThrottlingTest.java

@Test
public void throttleTest() throws InterruptedException {
    int messageCount = 200;
    CountDownLatch latch = new CountDownLatch(messageCount);

    DockerPort kafka = docker.containers().container("kafka").port(9092);
    ServiceProperties props = new ServiceProperties();
    props.addProperty(KAFKA_SERVER_KEY, kafka.inFormat("$HOST:$EXTERNAL_PORT"));

    String topic = "throttle-test";
    KafkaPublisherFactory publisherFactory = new KafkaPublisherFactory(props);
    KafkaPublisher publisher = publisherFactory.newBuilder(topic).build();

    KafkaSubscriberFactory subscriberFactory = new KafkaSubscriberFactory<String>(props);
    EventReceivedCallback<String> callback = (message, topicInfo) -> {
        latch.countDown();/*from w  w  w .  j a  v  a  2s.com*/
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };
    //noinspection unchecked
    subscriberFactory.newBuilder(topic, callback).withPollTime(50).withAutoCommit(true).build();

    for (int i = 0; i < messageCount; i++) {
        publisher.publishSync("message " + i + randomData());
    }
    latch.await();
}

From source file:ch.cyberduck.core.io.ThreadedStreamCloser.java

@Override
public void close(final OutputStream out) throws ConnectionTimeoutException {
    final CountDownLatch signal = new CountDownLatch(1);
    threadFactory.newThread(new Runnable() {
        @Override/*  w  ww.j a v  a2  s . co m*/
        public void run() {
            IOUtils.closeQuietly(out);
            signal.countDown();
        }
    }).start();
    try {
        if (!signal.await(preferences.getInteger("connection.timeout.seconds"), TimeUnit.SECONDS)) {
            throw new StreamCloseTimeoutException("Timeout closing output stream", null);
        }
    } catch (InterruptedException e) {
        throw new ConnectionTimeoutException(e.getMessage(), e);
    }
}

From source file:io.druid.server.initialization.JettyTest.java

@Test
@Ignore // this test will deadlock if it hits an issue, so ignored by default
public void testTimeouts() throws Exception {
    // test for request timeouts properly not locking up all threads
    final Executor executor = Executors.newFixedThreadPool(100);
    final AtomicLong count = new AtomicLong(0);
    final CountDownLatch latch = new CountDownLatch(1000);
    for (int i = 0; i < 10000; i++) {
        executor.execute(new Runnable() {
            @Override//from  w ww . jav a2 s  .  c o m
            public void run() {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        long startTime = System.currentTimeMillis();
                        long startTime2 = 0;
                        try {
                            ListenableFuture<StatusResponseHolder> go = client.go(
                                    new Request(HttpMethod.GET,
                                            new URL("http://localhost:" + port + "/slow/hello")),
                                    new StatusResponseHandler(Charset.defaultCharset()));
                            startTime2 = System.currentTimeMillis();
                            go.get();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            System.out.println("Response time client" + (System.currentTimeMillis() - startTime)
                                    + "time taken for getting future"
                                    + (System.currentTimeMillis() - startTime2) + "Counter "
                                    + count.incrementAndGet());
                            latch.countDown();

                        }
                    }
                });
            }
        });
    }

    latch.await();
}

From source file:aos.camel.RiderAutoPartsCallbackTest.java

@Test
public void testCallback() throws Exception {
    // related is the list of related items
    final List<String> relates = new ArrayList<String>();

    // latch to count down every time we got a reply
    final CountDownLatch latch = new CountDownLatch(numPartners);

    // use this callback to gather the replies and add it to the related list
    Synchronization callback = new SynchronizationAdapter() {
        @Override/* w w w .ja v  a  2 s  .  c o  m*/
        public void onComplete(Exchange exchange) {
            // get the reply and add it to related
            relates.add(exchange.getOut().getBody(String.class));
            // count down the latch
            latch.countDown();
        }

        @Override
        public void onFailure(Exchange exchange) {
            // count down the latch even if we failed
            latch.countDown();
        }
    };

    // send the same message to the business partners so they can return their feedback
    String body = "bumper";
    for (int i = 0; i < numPartners; i++) {
        template.asyncCallbackRequestBody("seda:partner:" + i, body, callback);
    }
    LOG.info("Send " + numPartners + " messages to partners.");

    // wait at most 1.5 seconds or until we got all replies
    boolean all = latch.await(1500, TimeUnit.MILLISECONDS);

    // log what we got as reply
    LOG.info("Got " + relates.size() + " replies, is all? " + all);
    for (String related : relates) {
        LOG.info("Related item category is: " + related);
    }

    // assert the unit test
    assertEquals(3, relates.size());
    assertEquals("bumper extension", relates.get(0));
    assertEquals("bumper filter", relates.get(1));
    assertEquals("bumper cover", relates.get(2));
}

From source file:com.netflix.curator.framework.imps.TestWithCluster.java

@Test
public void testReadOnly() throws Exception {
    System.setProperty("readonlymode.enabled", "true");
    try {/*from   w  ww. j  av a 2s  .  co  m*/
        Timing timing = new Timing();

        CuratorFramework client = null;
        TestingCluster cluster = new TestingCluster(2);
        try {
            cluster.start();

            client = CuratorFrameworkFactory.builder().connectString(cluster.getConnectString())
                    .canBeReadOnly(true).connectionTimeoutMs(timing.connection())
                    .sessionTimeoutMs(timing.session()).retryPolicy(new ExponentialBackoffRetry(100, 3))
                    .build();
            client.start();

            client.create().forPath("/test");

            final CountDownLatch readOnlyLatch = new CountDownLatch(1);
            final CountDownLatch reconnectedLatch = new CountDownLatch(1);
            ConnectionStateListener listener = new ConnectionStateListener() {
                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState) {
                    if (newState == ConnectionState.READ_ONLY) {
                        readOnlyLatch.countDown();
                    } else if (newState == ConnectionState.RECONNECTED) {
                        reconnectedLatch.countDown();
                    }
                }
            };
            client.getConnectionStateListenable().addListener(listener);

            InstanceSpec ourInstance = cluster
                    .findConnectionInstance(client.getZookeeperClient().getZooKeeper());
            Iterator<InstanceSpec> iterator = cluster.getInstances().iterator();
            InstanceSpec killInstance = iterator.next();
            if (killInstance.equals(ourInstance)) {
                killInstance = iterator.next(); // kill the instance we're not connected to
            }
            cluster.killServer(killInstance);

            Assert.assertEquals(reconnectedLatch.getCount(), 1);
            Assert.assertTrue(timing.awaitLatch(readOnlyLatch));

            Assert.assertEquals(reconnectedLatch.getCount(), 1);
            cluster.restartServer(killInstance);
            Assert.assertTrue(timing.awaitLatch(reconnectedLatch));
        } finally {
            IOUtils.closeQuietly(client);
            IOUtils.closeQuietly(cluster);
        }
    } finally {
        System.clearProperty("readonlymode.enabled");
    }
}

From source file:io.kahu.hawaii.util.call.dispatch.RequestDispatcher.java

public <T> Set<Response<T>> execute(RequestFactory<T> requestFactory, boolean waitForAnswers)
        throws ServerException {
    Set<Response<T>> responses = new HashSet<>();
    CountDownLatch latch = new CountDownLatch(requestFactory.getNumberOfRequests());
    AbortableRequest<T> request = requestFactory.getNextRequest();
    while (request != null) {
        request.setLatch(latch);//from ww  w  .  j a v a 2s . co m
        responses.add(executeAsync(request));
        request = requestFactory.getNextRequest();
    }

    if (waitForAnswers) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return responses;
}

From source file:co.cask.tigon.StandaloneMain.java

public StandaloneMain() {
    runLatch = new CountDownLatch(1);
    jarUnpackDir = Files.createTempDir();
    localDataDir = Files.createTempDir();
    CConfiguration cConf = CConfiguration.create();
    cConf.set(Constants.CFG_LOCAL_DATA_DIR, localDataDir.getAbsolutePath());
    Configuration hConf = new Configuration();

    Injector injector = Guice.createInjector(createModules(cConf, hConf));
    txService = injector.getInstance(TransactionManager.class);
    metricsCollectionService = injector.getInstance(MetricsCollectionService.class);
    deployClient = injector.getInstance(DeployClient.class);
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Before
public void setUp() throws Exception {
    directories = platformService.getBattleLobbyTempDirectories();
    if (!(directories.getRoot().exists() || directories.getRoot().mkdirs())) {
        fail("Could not create tmp root");
    }/*from   w  ww  .ja va  2 s .c o m*/

    // give file creation some time to complete
    Thread.sleep(250);

    tempWatcher = new RecursiveTempWatcher(directories);

    CountDownLatch latch = new CountDownLatch(1);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            tempWatcher.start();
            latch.countDown();
        }
    });
    if (!latch.await(1, TimeUnit.SECONDS)) {
        fail("Service did not start.");
    }
    // give watchers some time to wind up
    Thread.sleep(250);
}

From source file:org.apache.servicemix.jbi.cluster.engine.ReconnectTest.java

public void testLoadInOnly() throws Exception {
    createRoute(Transacted.Jms, true, false, false);

    final int nbThreads = 10;
    final int nbExchanges = 10;
    final ReadWriteLock lock = new ReentrantReadWriteLock();
    final CountDownLatch latch = new CountDownLatch(nbThreads);
    final AtomicInteger id = new AtomicInteger();
    lock.writeLock().lock();// w ww  .j  a  v a2  s .c  o m
    for (int i = 0; i < nbThreads; i++) {
        new Thread() {
            public void run() {
                Channel client = null;
                try {
                    client = nmr1.createChannel();
                    lock.readLock().lock();
                    for (int i = 0; i < nbExchanges; i++) {
                        Exchange exchange = client.createExchange(Pattern.InOnly);
                        exchange.getIn()
                                .setBody(new StringSource("<hello id='" + id.getAndIncrement() + "'/>"));
                        exchange.setTarget(nmr1.getEndpointRegistry()
                                .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME)));
                        client.sendSync(exchange);
                        assertEquals(Status.Done, exchange.getStatus());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                    latch.countDown();
                    if (client != null) {
                        client.close();
                    }
                }
            }
        }.start();
    }

    long t0, t1;

    cluster2.pause();

    t0 = System.currentTimeMillis();
    lock.writeLock().unlock();

    latch.await();

    broker.stop();
    cluster2.resume();

    Thread.sleep(500);
    broker = createBroker(false);

    receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT);
    //Thread.sleep(500);
    //receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT);

    t1 = System.currentTimeMillis();

    System.err.println("Elapsed time: " + (t1 - t0) + " ms");
    System.err.println("Throuput: " + (nbThreads * nbExchanges * 1000 / (t1 - t0)) + " messages/sec");
}

From source file:de.taimos.httputils.Tester1.java

/**
 * //from   w  w w  .  j a  va  2s .co m
 */
@Test
public void testGetAsyncStringCB() throws InterruptedException {
    final CountDownLatch cdl = new CountDownLatch(1);
    WS.url("http://www.heise.de").getAsync(new HTTPStringCallback() {

        @Override
        public void fail(Exception e) {
            System.out.println(e);
            Assert.fail();
            cdl.countDown();
        }

        @Override
        protected void invalidStatus(int status, HttpResponse response) {
            System.out.println("Invalid status: " + status);
            Assert.fail();
            cdl.countDown();
        }

        @Override
        protected void stringResponse(String body, HttpResponse response) {
            Assert.assertNotNull(body);
            Assert.assertFalse(body.isEmpty());
            cdl.countDown();
        }

    });
    Assert.assertTrue(cdl.await(10, TimeUnit.SECONDS));
}