Example usage for java.util.concurrent CountDownLatch countDown

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

Introduction

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

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

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

@Test
public void testListAllAsyncForPagination() throws Exception {
    Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    Flavor flavor2 = new Flavor();
    flavor2.setId("flavor2");
    flavor2.setKind("vm");

    Flavor flavor3 = new Flavor();
    flavor3.setId("flavor3");
    flavor3.setKind("vm");

    String nextPageLink = "nextPageLink";

    final ResourceList<Flavor> flavorResourceList = new ResourceList<>(Arrays.asList(flavor1, flavor2),
            nextPageLink, null);/*from w w  w.j a v  a  2  s .  c o m*/
    final ResourceList<Flavor> flavorResourceListNextPage = new ResourceList<>(Arrays.asList(flavor3));
    final ResourceList<Flavor> expectedFlavorResourceList = new ResourceList<>(
            Arrays.asList(flavor1, flavor2, flavor3));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavorResourceList);
    String serializedResponseNextPage = mapper.writeValueAsString(flavorResourceListNextPage);

    setupMocksForPagination(serializedResponse, serializedResponseNextPage, nextPageLink, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.listAllAsync(new FutureCallback<ResourceList<Flavor>>() {
        @Override
        public void onSuccess(@Nullable ResourceList<Flavor> result) {
            assertTrue(result.getItems().containsAll(expectedFlavorResourceList.getItems()));
            latch.countDown();
        }

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

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java

@Test
public void testReleaseBrokenBarrier() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    SteppableThread latchStepper = new SteppableWaitForLatch(latch);

    interruptInWait(latchStepper, TestMode.RELEASE);

    try {//from  w ww.  j a va  2s.  c o m
        latchStepper.release();
        Assert.fail();
    } catch (RuntimeException e) {
        Assert.assertEquals(BrokenBarrierException.class, e.getCause().getClass());
    }

    ((CyclicBarrier) ReflectionTestUtils.getField(latchStepper, "stepStart")).reset();
    latchStepper.start();
    latch.countDown();
    latchStepper.releaseAndJoin();
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_post_load_interceptors() throws Exception {

    CompleteBean entity = builder().randomId().name("DuyHai").label("label").buid();

    asyncManager.insert(entity).getImmediately();

    final CountDownLatch latch = new CountDownLatch(1);

    final AchillesFuture<CompleteBean> future = asyncManager.find(CompleteBean.class, entity.getId(),
            withAsyncListeners(new FutureCallback<Object>() {
                @Override/*from   www.j a v  a  2 s  . co  m*/
                public void onSuccess(Object result) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable t) {

                }
            }));

    latch.await();

    assertThat(future.get().getLabel()).isEqualTo("postLoad");
}

From source file:ufo.remote.calls.benchmark.client.caller.vertx.VertxClusterTester.java

@PostConstruct
public void init() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final VertxOptions options = new VertxOptions();
    final Config conf = new Config();
    Vertx.clusteredVertx(options.setClusterHost("localhost").setClusterPort(0).setClustered(true)
            .setClusterManager(new HazelcastClusterManager(conf)), ar -> {
                if (ar.failed()) {
                    logger.error("Error starting Vertx cluster", ar.cause());
                }/* w  w  w .j  a va 2s .  co m*/
                logger.info("Vertx cluster node started [{}]");
                vertx = ar.result();
                logger.info("Initialising vertx verticles...");
                latch.countDown();
            });
    latch.await();
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncBatchModeIT.java

@Test
public void should_reinit_batch_context_and_consistency_after_exception_async() throws Exception {
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("simple_tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("simple_tweet2").buid();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override//from w w w  .j a  v  a  2s .c  o m
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

    asyncManager.insert(tweet1);

    // Start batch
    AsyncBatch batch = asyncManager.createBatch();

    batch.startBatch(EACH_QUORUM);
    batch.insert(tweet2);

    batch.asyncEndBatch(successCallBack);

    latch.await();

    assertThatBatchContextHasBeenReset(batch);

    logAsserter.prepareLogLevelForDriverConnection();
    batch.startBatch();
    batch.insert(tweet2);
    batch.asyncEndBatch();
    logAsserter.assertConsistencyLevels(ONE);

    assertThat(successSpy.get()).isEqualTo(Empty.INSTANCE);
}

From source file:com.dangdang.ddframe.job.internal.job.dataflow.AbstractDataFlowElasticJob.java

@SuppressWarnings("unchecked")
private void processDataForSequence(final JobExecutionMultipleShardingContext shardingContext,
        final Map<Integer, List<T>> data) {
    final CountDownLatch latch = new CountDownLatch(data.size());
    for (final Entry<Integer, List<T>> each : data.entrySet()) {
        executorService.submit(new Runnable() {

            @Override//from w  ww . j  av a2 s .c  o  m
            public void run() {
                try {
                    processDataWithStatistics(
                            (C) shardingContext.createJobExecutionSingleShardingContext(each.getKey()),
                            each.getValue());
                } finally {
                    latch.countDown();
                }
            }
        });
    }
    latchAwait(latch);
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncBatchModeIT.java

@Test
public void should_batch_with_custom_consistency_level_async() throws Exception {
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("simple_tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("simple_tweet2").buid();
    Tweet tweet3 = TweetTestBuilder.tweet().randomId().content("simple_tweet3").buid();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override//from   www . j  a v a2  s.c o  m
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

    asyncManager.insert(tweet1).getImmediately();

    // Start batch
    AsyncBatch batch = asyncManager.createBatch();

    batch.startBatch(QUORUM);

    logAsserter.prepareLogLevelForDriverConnection();

    Tweet foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately();

    assertThat(foundTweet1.getContent()).isEqualTo(tweet1.getContent());

    batch.insert(tweet2);
    batch.insert(tweet3);

    batch.asyncEndBatch(successCallBack);

    latch.await();

    logAsserter.assertConsistencyLevels(QUORUM);
    assertThatBatchContextHasBeenReset(batch);

    assertThat(successSpy.get()).isSameAs(Empty.INSTANCE);
}

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

@Test
public void testThreadedLeaseIncrease() throws Exception {
    final Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {//from   ww w  .j a  v  a 2  s.  com
        client.start();

        final SharedCount count = new SharedCount(client, "/foo/count", 1);
        count.start();

        final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", count);

        ExecutorService service = Executors.newCachedThreadPool();

        final CountDownLatch latch = new CountDownLatch(1);
        Future<Object> future1 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Lease lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS);
                Assert.assertNotNull(lease);
                latch.countDown();
                lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS);
                Assert.assertNotNull(lease);
                return null;
            }
        });
        Future<Object> future2 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Assert.assertTrue(latch.await(timing.seconds(), TimeUnit.SECONDS));
                timing.sleepABit(); // make sure second acquire is waiting
                Assert.assertTrue(count.trySetCount(2));
                return null;
            }
        });

        future1.get();
        future2.get();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.manpowergroup.cn.icloud.util.Case1.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

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

            public void run() {
                try {
                    startLatch.await();//from  w ww.  jav a2  s  .c o  m

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

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

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

}

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_post_load_interceptor_on_typed_query() throws Exception {
    // Given/*from ww w . j a  v a  2s  . co  m*/
    CompleteBean entity = builder().randomId().name("DuyHai").label("label").buid();

    asyncManager.insert(entity).getImmediately();

    RegularStatement statement = select().from("CompleteBean").where(eq("id", bindMarker()));

    // When
    final CountDownLatch latch = new CountDownLatch(1);
    final AchillesFuture<CompleteBean> future = asyncManager
            .typedQuery(CompleteBean.class, statement, entity.getId()).getFirst(new FutureCallback<Object>() {
                @Override
                public void onSuccess(Object result) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable t) {

                }
            });

    latch.await();

    // Then
    assertThat(future.get().getLabel()).isEqualTo("postLoad");
}