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.netflix.curator.framework.recipes.queue.TestDistributedIdQueue.java

@Test
public void testDeletingWithLock() throws Exception {
    DistributedIdQueue<TestQueueItem> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();//from   w w w .ja va  2 s .  c  o m
    try {
        final CountDownLatch consumingLatch = new CountDownLatch(1);
        final CountDownLatch waitLatch = new CountDownLatch(1);
        QueueConsumer<TestQueueItem> consumer = new QueueConsumer<TestQueueItem>() {
            @Override
            public void consumeMessage(TestQueueItem message) throws Exception {
                consumingLatch.countDown();
                waitLatch.await();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks")
                .buildIdQueue();
        queue.start();

        queue.put(new TestQueueItem("test"), "id");

        Assert.assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it
        Assert.assertEquals(queue.remove("id"), 0);

        waitLatch.countDown();
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.vmware.photon.controller.api.client.resource.AuthApiTest.java

@Test
public void testGetAuthStatusAsync() throws IOException, InterruptedException {
    final Auth auth = new Auth();

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(auth);

    setupMocks(serialized, HttpStatus.SC_OK);

    AuthApi authApi = new AuthApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    authApi.getAuthStatusAsync(new FutureCallback<Auth>() {
        @Override/*from  w  w  w .ja v a2s .  com*/
        public void onSuccess(@Nullable Auth result) {
            assertEquals(result, auth);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });
}

From source file:com.gopivotal.cla.github.RateLimitingClientHttpRequestInterceptorTest.java

@Test
public void block() throws InterruptedException, IOException {
    CountDownLatch latch = new CountDownLatch(1);

    MockClientHttpRequest request = new MockClientHttpRequest();
    MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.OK);
    ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);

    request.setMethod(HttpMethod.GET);/*from w  w w.  j a va2  s .  c o  m*/
    request.setURI(URI.create("http://localhost"));

    when(execution.execute(request, new byte[0])).thenReturn(response);

    new Thread(new Trigger(this.interceptor, latch)).start();
    latch.await();

    this.interceptor.intercept(request, new byte[0], execution);
}

From source file:ufo.remote.calls.benchmark.client.caller.resttemplate.AsyncRestTemplateTester.java

@Override
protected void startTest(final TesterResult result) {

    String url = "http://" + hostname + ":" + port + path;

    CountDownLatch latch = new CountDownLatch(result.totalCalls);
    AtomicInteger failures = new AtomicInteger(0);
    Executor executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < result.totalCalls; i++) {
        executor.execute(new Caller(url, result.message, latch, failures));
    }//from w ww .ja v  a2 s .c o  m

    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    result.failures = failures.get();
}

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

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

    CuratorFramework client = null;//from   www  . ja v  a 2  s .  c o m
    PathChildrenCache cache = null;
    TestingCluster cluster = new TestingCluster(3);
    try {
        cluster.start();

        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/test");

        cache = new PathChildrenCache(client, "/test", false);
        cache.start();

        final CountDownLatch resetLatch = new CountDownLatch(1);
        final CountDownLatch reconnectLatch = new CountDownLatch(1);
        final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>(
                new CountDownLatch(3));
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED) {
                    resetLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) {
                    reconnectLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    latch.get().countDown();
                }
            }
        });

        client.create().forPath("/test/one");
        client.create().forPath("/test/two");
        client.create().forPath("/test/three");

        Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS));

        InstanceSpec connectionInstance = cluster
                .findConnectionInstance(client.getZookeeperClient().getZooKeeper());
        cluster.killServer(connectionInstance);

        Assert.assertTrue(timing.awaitLatch(reconnectLatch));

        Assert.assertEquals(cache.getCurrentData().size(), 3);
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
        IOUtils.closeQuietly(cluster);
    }
}

From source file:com.vmware.photon.controller.api.client.resource.AuthRestApiTest.java

@Test
public void testGetAuthStatusAsync() throws IOException, InterruptedException {
    final Auth auth = new Auth();

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(auth);

    setupMocks(serialized, HttpStatus.SC_OK);

    AuthApi authApi = new AuthRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    authApi.getAuthStatusAsync(new FutureCallback<Auth>() {
        @Override/*from   w  w w  .j  a v  a 2  s.  c o m*/
        public void onSuccess(@Nullable Auth result) {
            assertEquals(result, auth);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });
}

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

@Override
protected void setUp() throws Exception {
    super.setUp();
    final ICalendars cals = Me.getCalendars();
    final CountDownLatch cdl = new CountDownLatch(1);
    // an empty iterator will be returned for any entity set unless you call fetch()
    Futures.addCallback(cals.fetchAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            cdl.countDown();//from  w ww  .j ava 2 s .com
        }

        public void onSuccess(Void result) {
            Iterator<ICalendar> iterator = cals.iterator();
            if (iterator.hasNext()) {
                calendar = iterator.next();
            }
            cdl.countDown();
        }
    });

    cdl.await(60000, TimeUnit.MILLISECONDS);
    if (calendar == null) {
        fail("No calendar found");
    }
}

From source file:alluxio.proxy.AlluxioProxyProcess.java

/**
 * Creates an instance of {@link AlluxioProxy}.
 */
AlluxioProxyProcess() {
    mStartTimeMs = System.currentTimeMillis();
    mLatch = new CountDownLatch(1);
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java

@Test
public void testGetParticipantNodes() throws Exception {
    final int READERS = 20;
    final int WRITERS = 8;

    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {/*from  ww w .ja va  2s  .c  o  m*/
        client.start();

        final CountDownLatch latch = new CountDownLatch(READERS + WRITERS);
        final CountDownLatch readLatch = new CountDownLatch(READERS);
        final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");

        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < READERS; ++i) {
            service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    lock.readLock().acquire();
                    latch.countDown();
                    readLatch.countDown();
                    return null;
                }
            });
        }
        for (int i = 0; i < WRITERS; ++i) {
            service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Assert.assertTrue(readLatch.await(10, TimeUnit.SECONDS));
                    latch.countDown(); // must be before as there can only be one writer
                    lock.writeLock().acquire();
                    return null;
                }
            });
        }

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        Collection<String> readers = lock.readLock().getParticipantNodes();
        Collection<String> writers = lock.writeLock().getParticipantNodes();

        Assert.assertEquals(readers.size(), READERS);
        Assert.assertEquals(writers.size(), WRITERS);
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.cisco.oss.foundation.monitoring.service.TestMultiService.java

@Test
public void testManyServices() throws Exception {

    MonitoringAgentFactory.getInstance().register(
            new PropertiesConfiguration(TestMultiService.class.getResource("/config.properties").getPath()));

    ExecutorService threadPool = Executors.newFixedThreadPool(10);

    int numOfServices = 1234;

    final CountDownLatch latch = new CountDownLatch(numOfServices);

    final ServiceDetails serviceDetails = new ServiceDetails("default desc", "test", "junit", 12345);
    for (int i = 0; i < numOfServices; i++) {

        final int index = i;

        threadPool.execute(new Runnable() {

            @Override/*from   w ww  . ja  v a2 s . c o  m*/
            public void run() {
                String apiName = (index % 3) + "";
                CommunicationInfo.getCommunicationInfo().transactionStarted(serviceDetails, apiName, 125);
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, apiName,
                        (index % 2 == 0) ? false : true, "kuku");
                latch.countDown();
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    int numberOfThreads = Thread.getAllStackTraces().keySet().size();
    Assert.assertTrue(numberOfThreads <= 30);

    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    Collection<Service> services = ServiceInfo.INSTANCE.getServices();
    System.out.println("services: " + services.size());

    for (Service service : services) {
        System.out.println("service: " + service + ". total: " + service.getTotalRequestCount());
    }

    Assert.assertEquals(3, services.size());

    //        try {
    //            Thread.sleep(60000);
    //        } catch (InterruptedException e) {
    //            e.printStackTrace();
    //        }

}