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.palantir.docker.compose.DockerComposeRuleShould.java

@SuppressWarnings("unchecked")
@Test/*w  w  w . ja  va 2 s. c  om*/
public void be_able_to_save_logs_to_a_directory_while_containers_are_running()
        throws IOException, InterruptedException {
    File logLocation = logFolder.newFolder();
    DockerComposeRule loggingComposition = DockerComposeRule.builder().from(rule)
            .saveLogsTo(logLocation.getAbsolutePath()).build();
    when(dockerCompose.ps()).thenReturn(TestContainerNames.of("db"));
    CountDownLatch latch = new CountDownLatch(1);
    when(dockerCompose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> {
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("db log", outputStream);
        latch.countDown();
        return true;
    });
    loggingComposition.before();
    assertThat(latch.await(1, TimeUnit.SECONDS), is(true));
    loggingComposition.after();
    assertThat(logLocation.listFiles(), arrayContaining(fileWithName("db.log")));
    assertThat(new File(logLocation, "db.log"), is(fileContainingString("db log")));
}

From source file:de.hybris.platform.masterserver.impl.DefaultStatisticsGatewayTest.java

@Test
public void shouldUpdateLoggedInBackOfficeUsersConcurrently() throws InterruptedException {
    // given/*w w  w  . jav a 2 s .c om*/
    generateStats = true;
    given(businessCollector.collectStatistics()).willReturn(null);
    given(systemCollector.collectStatistics()).willReturn(null);
    given(encryptor.encrypt(eq("{\"session\":{\"backOfficeOverallUsers\":{\"hac\":500}}}"), anyString()))
            .willReturn(statisticsPayload);
    final CountDownLatch latch = new CountDownLatch(500);

    // when
    for (int i = 0; i < 500; i++) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    statGateway.updateLoggedInUsersStats("/hac");
                } finally {
                    latch.countDown();
                }
            }
        }).start();
    }
    latch.await();
    final StatisticsPayload encodedStatistics = statGateway.getStatisticsPayload();

    // then
    assertThat(encodedStatistics).isNotNull();
}

From source file:com.microsoft.office.core.FolderAsyncTestCase.java

private void readAndCheck() throws Exception {
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getFolders().getAsync(folder.getId()), new FutureCallback<IFolder>() {
        @Override/* w  w  w.j a v  a 2  s . c om*/
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IFolder result) {
            try {
                folder = result;
                Class<?> cls = folder.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceFolder.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(property.getPrimitiveValue().toValue(), getter.invoke(folder));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:io.undertow.server.handlers.GracefulShutdownTestCase.java

@Test
public void simpleGracefulShutdownTestCase() throws IOException, InterruptedException {

    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
    TestHttpClient client = new TestHttpClient();
    try {/*from  w w w  .  ja  v  a  2 s.  com*/
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

        shutdown.shutdown();

        result = client.execute(get);
        Assert.assertEquals(StatusCodes.SERVICE_UNAVAILABLE, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

        shutdown.start();

        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

        CountDownLatch latch = new CountDownLatch(1);
        latch2.set(latch);

        latch1.set(new CountDownLatch(1));
        Thread t = new Thread(new RequestTask());
        t.start();
        latch1.get().await();
        shutdown.shutdown();

        Assert.assertFalse(shutdown.awaitShutdown(10));

        latch.countDown();

        Assert.assertTrue(shutdown.awaitShutdown(10000));

    } finally {
        client.getConnectionManager().shutdown();
    }

}

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

@Test
public void testGetHostsAsync() throws IOException, InterruptedException {
    Vm vm1 = new Vm();
    vm1.setId("vm1");

    Vm vm2 = new Vm();
    vm2.setId("vm2");

    final ResourceList<Vm> vmList = new ResourceList<>(Arrays.asList(vm1, vm2));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(vmList);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    DeploymentApi deploymentApi = new DeploymentApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.getAllDeploymentVmsAsync("foo", new FutureCallback<ResourceList<Vm>>() {
        @Override//w  w  w .  j av  a  2s  . c om
        public void onSuccess(ResourceList<Vm> result) {
            assertEquals(result.getItems(), vmList.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:io.fabric8.agent.DownloadManagerTest.java

@Test
public void testDownloadUsingNonAuthenticatedProxy() throws Exception {
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//w  ww .  ja  v a2 s.  c o  m
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getOutputStream().write(new byte[] { 0x42 });
            response.getOutputStream().close();
        }
    });
    server.start();

    Properties custom = new Properties();
    custom.setProperty("org.ops4j.pax.url.mvn.proxySupport", "true");
    String settings = createMavenSettingsWithProxy(server.getConnectors()[0].getLocalPort());
    DownloadManager dm = createDownloadManager("http://relevant.not/maven2@id=central", settings, custom);

    try {
        final CountDownLatch latch = new CountDownLatch(1);
        DownloadFuture df = dm.download("mvn:x.y/z/1.0");
        df.addListener(new FutureListener<DownloadFuture>() {
            @Override
            public void operationComplete(DownloadFuture future) {
                latch.countDown();
            }
        });

        latch.await(30, TimeUnit.SECONDS);
        assertNotNull(df.getUrl());
        assertNotNull(df.getFile());
        assertEquals("z-1.0.jar", df.getFile().getName());
        LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile());
    } finally {
        server.stop();
    }
}

From source file:com.twitter.common.zookeeper.GroupTest.java

@Test
public void testSessionExpirationTriggersOnLoseMembership() throws Exception {
    final CountDownLatch lostMembership = new CountDownLatch(1);
    Command onLoseMembership = new Command() {
        @Override//from w  w  w  .j a  va2 s.  com
        public void execute() throws RuntimeException {
            lostMembership.countDown();
        }
    };
    assertEmptyMembershipObserved();

    Membership membership = group.join(onLoseMembership);
    assertMembershipObserved(membership.getMemberId());
    expireSession(zkClient);

    lostMembership.await(); // Will hang this test if onLoseMembership event is not propagated.
}

From source file:com.twitter.common.zookeeper.GroupTest.java

@Test
public void testNodeDeleteTriggersOnLoseMembership() throws Exception {
    final CountDownLatch lostMembership = new CountDownLatch(1);
    Command onLoseMembership = new Command() {
        @Override/*from   w  w  w.  jav  a2 s  . co m*/
        public void execute() throws RuntimeException {
            lostMembership.countDown();
        }
    };
    assertEmptyMembershipObserved();

    Membership membership = group.join(onLoseMembership);
    assertMembershipObserved(membership.getMemberId());
    membership.cancel();

    lostMembership.await(); // Will hang this test if onLoseMembership event is not propagated.
}

From source file:io.fabric8.agent.DownloadManagerTest.java

@Test
public void testDownloadUsingAuthenticatedProxy() throws Exception {
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override/*from ww  w  .  java  2s  .  c  om*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String proxyAuth = request.getHeader("Proxy-Authorization");
            if (proxyAuth == null || proxyAuth.trim().equals("")) {
                response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
                response.addHeader("Proxy-Authenticate", "Basic realm=\"Proxy Server\"");
                baseRequest.setHandled(true);
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(new byte[] { 0x42 });
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    Properties custom = new Properties();
    custom.setProperty("org.ops4j.pax.url.mvn.proxySupport", "true");
    String settings = createMavenSettingsWithProxy(server.getConnectors()[0].getLocalPort());
    DownloadManager dm = createDownloadManager("http://relevant.not/maven2@id=central", settings, custom);

    try {
        final CountDownLatch latch = new CountDownLatch(1);
        DownloadFuture df = dm.download("mvn:x.y/z/1.0");
        df.addListener(new FutureListener<DownloadFuture>() {
            @Override
            public void operationComplete(DownloadFuture future) {
                latch.countDown();
            }
        });

        latch.await(30, TimeUnit.SECONDS);
        assertNotNull(df.getUrl());
        assertNotNull(df.getFile());
        assertEquals("z-1.0.jar", df.getFile().getName());
        LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile());
    } finally {
        server.stop();
    }
}

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

@Test
public void testDeleteAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    DisksApi disksApi = new DisksApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    disksApi.deleteAsync("persistentDisk", new FutureCallback<Task>() {
        @Override/*  ww w. j  a  v  a  2 s . c o  m*/
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

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

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