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.predic8.membrane.examples.tests.integration.OAuth2RaceCondition.java

@Test
public void testSessionIdStateRaceCondition() throws Exception {
    HttpClient hc = HttpClientBuilder.create().build();

    login(hc);//from ww w  .  j  a va2  s  .c o  m
    System.out.println("Logged in");
    ExecutorService executor = Executors.newFixedThreadPool(2);
    for (int i = 0; i < 10; i++) {

        //            HttpClient hc1 = HttpClientBuilder.create().build();
        //            login(hc1);
        Future<Exception>[] results = new Future[2];

        int parallelReqs = 2;
        CountDownLatch cdl = new CountDownLatch(parallelReqs);

        for (int j = 0; j < parallelReqs; j++) {
            final int fj = j;
            results[j] = executor.submit(() -> {
                try {
                    int uri = (fj % 2 == 0 ? 1 : 2);
                    String url = "http://localhost:2011/test" + uri;
                    HttpGet get = new HttpGet(url);
                    //setNoRedirects(get);
                    cdl.countDown();
                    cdl.await();
                    try (CloseableHttpResponse getRes = (CloseableHttpResponse) hc.execute(get)) {
                        assertEquals(200, getRes.getStatusLine().getStatusCode());
                        String resText = EntityUtils.toString(getRes.getEntity(), "UTF-8");
                        System.out.println("Called: Test" + uri + ".\nActual: " + resText);
                        assertTrue(resText.contains(Integer.toString(uri)));
                    }
                    return null;
                } catch (Exception e) {
                    return e;
                }
            });
        }
        for (int j = 0; j < parallelReqs; j++) {
            results[j].get();
        }

        for (int j = 0; j < parallelReqs; j++) {
            Exception e = results[j].get();
            if (e != null)
                throw new RuntimeException(e);
        }

    }
    executor.shutdown();
}

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

public void testRead() {
    prepareEvent();/*ww w  . ja  va  2s .  com*/
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                readAndCheck();
                removeEvent();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });

    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testRead() timed out");
        }
    } catch (InterruptedException e) {
        fail("testRead() has been interrupted");
    }
}

From source file:com.playhaven.android.diagnostic.test.PHTestCase.java

protected void enableThreadedTesting(Object toTest) {
    latches.put(toTest.getClass().getSimpleName(), new CountDownLatch(1));
}

From source file:ch.windmobile.server.socialmodel.mogodb.HeavyLoadTest.java

public void testFullChatCycle() throws Exception {
    ServiceLocator locator = new MongoDBServiceLocator().connect(null);
    try {/*  w  w w  . j a  v a 2 s . c  o m*/
        final int CNT = 50000;
        final Executor executor = Executors.newFixedThreadPool(10);
        final ChatService chatService = locator.getService(ChatService.class);
        final AtomicInteger counter = new AtomicInteger();
        final CountDownLatch latch = new CountDownLatch(CNT);
        for (int i = 0; i < CNT; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    chatService.postMessage("TestRoom", "aUser",
                            "Hello, this is my message " + counter.incrementAndGet(), "");
                    latch.countDown();
                }
            });
        }
        System.out.println("Chat sent, waiting for the end...");
        latch.await(2, TimeUnit.MINUTES);
        Messages ret = chatService.findMessages("TEST", 5);
        System.out.println("result : " + ret);
    } finally {
        locator.disconnect();
    }
}

From source file:example.springdata.mongodb.people.RxJava2PersonRepositoryIntegrationTest.java

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 *///from  w  ww .  j  a  v a  2 s  . co  m
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    Flowable<Person> people = Flowable.just(new Person("Hank", "Schrader", 43), //
            new Person("Mike", "Ehrmantraut", 62));

    repository.count() //
            .doOnSuccess(System.out::println) //
            .toFlowable() //
            .switchMap(count -> repository.saveAll(people)) //
            .lastElement() //
            .toSingle() //
            .flatMap(v -> repository.count()) //
            .doOnSuccess(System.out::println) //
            .doAfterTerminate(countDownLatch::countDown) //
            .doOnError(throwable -> countDownLatch.countDown()) //
            .subscribe();

    countDownLatch.await();
}

From source file:com.flipkart.flux.deploymentunit.ExecutableRegistryPopulator.java

@Override
public void initialize() {

    //count down latch to parallelly populate executable registry from multiple deployment units
    CountDownLatch duCountDownLatch = new CountDownLatch(deploymentUnitsMap.size());

    //for each deployment unit, start a new thread which populates executable registry
    for (Map.Entry<String, DeploymentUnit> deploymentUnitEntry : deploymentUnitsMap.entrySet()) {
        new Thread(new ExecutableRegistryLoader(deploymentUnitEntry.getKey(), deploymentUnitEntry.getValue(),
                duCountDownLatch)).start();
    }//w  w  w.  j  a v a 2s .c  om

    try {
        duCountDownLatch.await(); //wait until all deployment units' tasks are loaded into executable registry
    } catch (InterruptedException e) {
        LOGGER.error(
                "Unable to populate executable registry. Deployment unit count down latch has been interrupted. Exception: {}",
                e.getMessage());
        throw new FluxError(FluxError.ErrorType.runtime,
                "Unable to populate executable registry. Deployment unit count down latch has been interrupted.",
                e);
    }
}

From source file:com.yahoo.gondola.container.client.ZookeeperShardManagerClientTest.java

@BeforeMethod
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    servers = new HashMap<>();
    shardManagers = new HashMap<>();
    for (String hostId : config.getHostIds()) {
        Gondola gondola = mock(Gondola.class);
        when(gondola.getHostId()).thenReturn(hostId);
        when(gondola.getConfig()).thenReturn(config);
        ShardManager shardManager = mock(ShardManager.class);
        ZookeeperShardManagerServer server = new ZookeeperShardManagerServer("foo",
                zookeeperServer.getConnectString(), gondola, shardManager);
        shardManagers.put(hostId, shardManager);
        servers.put(hostId, server);/*  w ww . jav  a2s .  c o m*/
    }

    client = new ZookeeperShardManagerClient("foo", "fooClientName", zookeeperServer.getConnectString(),
            config);
    stats = (PathChildrenCache) Whitebox.getInternalState(client, "stats");
    CountDownLatch latch = new CountDownLatch(1);
    this.stats.getListenable().addListener((curatorFramework, pathChildrenCacheEvent) -> {
        if (this.stats.getCurrentData().size() == config.getMembers().size()) {
            latch.countDown();
        }
    });
    latch.await();
}

From source file:com.ericsson.gerrit.plugins.highavailability.index.AbstractIndexForwardingIT.java

@Test
@UseLocalDisk/*from   w  ww.  j a  va  2  s .  co m*/
@GlobalPluginConfig(pluginName = "high-availability", name = "peerInfo.static.url", value = URL)
@GlobalPluginConfig(pluginName = "high-availability", name = "http.retryInterval", value = "100")
public void testIndexForwarding() throws Exception {
    String expectedRequest = getExpectedRequest();
    CountDownLatch expectedRequestLatch = new CountDownLatch(1);
    wireMockRule.addMockServiceRequestListener((request, response) -> {
        if (request.getAbsoluteUrl().contains(expectedRequest)) {
            expectedRequestLatch.countDown();
        }
    });
    givenThat(post(urlEqualTo(expectedRequest)).willReturn(aResponse().withStatus(HttpStatus.SC_NO_CONTENT)));
    doAction();
    assertThat(expectedRequestLatch.await(5, TimeUnit.SECONDS)).isTrue();
    verify(postRequestedFor(urlEqualTo(expectedRequest)));
}

From source file:org.springframework.cloud.stream.config.MessageChannelConfigurerTests.java

@Test
public void testMessageConverterConfigurer() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    MessageHandler messageHandler = new MessageHandler() {
        @Override/*from  w  ww  .j a  va2 s  .  c om*/
        public void handleMessage(Message<?> message) throws MessagingException {
            assertThat(message.getPayload()).isInstanceOf(Tuple.class);
            assertThat(((Tuple) message.getPayload()).getFieldNames().get(0)).isEqualTo("message");
            assertThat(((Tuple) message.getPayload()).getValue(0)).isEqualTo("Hi");
            latch.countDown();
        }
    };
    testSink.input().subscribe(messageHandler);
    testSink.input().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}").build());
    assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
    testSink.input().unsubscribe(messageHandler);
}

From source file:com.qualys.jserf.SerfClientIT.java

@Test(timeout = 10000)
public void testStats() throws Exception {
    while (!client.isConnected()) {
        Thread.sleep(500);//  w ww.j  a  v  a 2s  . co  m
    }
    final boolean[] callbackInvoked = { false };
    final CountDownLatch latch = new CountDownLatch(1);

    SerfResponseCallBack<StatsResponseBody> callBack = new SerfResponseCallBack<StatsResponseBody>() {
        @Override
        public void call(SerfResponse<StatsResponseBody> response) {
            log.debug("Received call back with sequence {}", response.getHeader().getSeq());
            callbackInvoked[0] = true;

            assertNotNull(response.getHeader());
            assertEquals(StringUtils.EMPTY, response.getHeader().getError());
            assertEquals(StatsResponseBody.class, response.getBody().getClass());
            assertNotNull(response.getBody());

            StatsResponseBody body = response.getBody();
            log.debug("body={}", body);
            assertNotNull(body.getAgent());
            assertNotNull(body.getRuntime());
            assertNotNull(body.getSerf());
            assertNotNull(body.getTags());

            //don't count down unless all the asserts pass
            latch.countDown();
        }
    };

    SerfRequest request = SerfRequests.stats(callBack);

    client.makeRpc(request);
    latch.await();

    assertTrue(callbackInvoked[0]);
}