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:io.undertow.server.handlers.sse.ServerSentEventTestCase.java

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

    final Socket socket = new Socket(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"));
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch connected = new CountDownLatch(1);
    DefaultServer.setRootHandler(new ServerSentEventHandler(new ServerSentEventConnectionCallback() {
        @Override/*  www .  j av  a 2s.  com*/
        public void connected(final ServerSentEventConnection connection, final String lastEventId) {
            final XnioIoThread thread = (XnioIoThread) Thread.currentThread();
            connected.countDown();
            thread.execute(new Runnable() {
                @Override
                public void run() {
                    connection.send("hello", new ServerSentEventConnection.EventCallback() {
                        @Override
                        public void done(ServerSentEventConnection connection, String data, String event,
                                String id) {
                        }

                        @Override
                        public void failed(ServerSentEventConnection connection, String data, String event,
                                String id, IOException e) {
                            latch.countDown();
                        }
                    });
                    if (latch.getCount() > 0) {
                        WorkerUtils.executeAfter(thread, this, 100, TimeUnit.MILLISECONDS);
                    }
                }
            });
        }
    }));
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    out.write(("GET / HTTP/1.1\r\nHost:" + DefaultServer.getHostAddress() + "\r\n\r\n").getBytes());
    out.flush();
    if (!connected.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
    out.close();
    in.close();
    if (!latch.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
}

From source file:nl.edia.xapi.proxy.StatementMethodInterceptorTest.java

@Test
public void test1a() throws Throwable {
    MethodInvocation mock = Mockito.mock(MethodInvocation.class);
    when(mock.getMethod()).thenReturn(getMethod("doSomeThing1a"));
    when(mock.getArguments()).thenReturn(
            new Object[] { Mockito.mock(User.class), Mockito.mock(Course.class), Mockito.mock(Module.class) });
    assertTrue(isaSync());//from   w  ww .ja  v  a2s. co  m
    {
        final CountDownLatch latch = new CountDownLatch(1);
        when(statementClient.postStatement(Mockito.any(gov.adlnet.xapi.model.Statement.class)))
                .then(new Answer<String>() {

                    @Override
                    public String answer(InvocationOnMock invocation) throws Throwable {
                        latch.countDown();
                        return "OK";
                    }
                });
        invoke(mock);
        assertTrue(latch.await(10, TimeUnit.SECONDS));
        verify(this.statementClientFactory, Mockito.times(1)).build(Mockito.eq(mock), Mockito.any());
        verify(statementClient, Mockito.times(1))
                .postStatement(Mockito.any(gov.adlnet.xapi.model.Statement.class));
    }

    // Without sync
    setaSync(false);
    assertFalse(isaSync());
    invoke(mock);
    verify(this.statementClientFactory, Mockito.times(2)).build(Mockito.eq(mock), Mockito.any());
    verify(statementClient, Mockito.times(2)).postStatement(Mockito.any(gov.adlnet.xapi.model.Statement.class));

    when(statementClient.postStatement(Mockito.any(gov.adlnet.xapi.model.Statement.class)))
            .thenThrow(IOException.class);
    // Try an exception async false
    setaSync(false);
    assertFalse(isaSync());
    invoke(mock);
    verify(this.statementClientFactory, Mockito.times(3)).build(Mockito.eq(mock), Mockito.any());
    verify(statementClient, Mockito.times(3)).postStatement(Mockito.any(gov.adlnet.xapi.model.Statement.class));
    {
        // Try an exception async true
        setaSync(true);
        assertTrue(isaSync());
        final CountDownLatch latch = new CountDownLatch(1);
        Mockito.reset(statementClient);
        when(statementClient.postStatement(Mockito.any(gov.adlnet.xapi.model.Statement.class)))
                .then(new Answer<String>() {

                    @Override
                    public String answer(InvocationOnMock invocation) throws Throwable {
                        latch.countDown();
                        return "OK";
                    }
                });
        invoke(mock);
        assertTrue(latch.await(10, TimeUnit.SECONDS));
        verify(this.statementClientFactory, Mockito.times(4)).build(Mockito.eq(mock), Mockito.any());
        verify(statementClient, Mockito.times(1))
                .postStatement(Mockito.any(gov.adlnet.xapi.model.Statement.class));
    }

}

From source file:camelinaction.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//from  w  w  w . j a  va2 s  .c  o  m
        public void onComplete(Exchange exchange) {
            // get the reply and add it to related
            String body = exchange.getOut().getBody(String.class);
            relates.add(body);

            log.info("Get async reply {}", body);

            // 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 2 seconds or until we got all replies
    boolean all = latch.await(2000, 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.metamx.emitter.core.EmitterTest.java

@Test
public void testTimeBasedEmission() throws Exception {
    final int timeBetweenEmissions = 100;
    emitter = timeBasedEmitter(timeBetweenEmissions);

    final CountDownLatch latch = new CountDownLatch(1);

    httpClient.setGoHandler(new GoHandler() {
        @Override/*from  ww w. j av  a 2  s. c o  m*/
        public <Intermediate, Final> ListenableFuture<Final> go(Request intermediateFinalRequest,
                HttpResponseHandler<Intermediate, Final> handler) throws Exception {
            latch.countDown();
            return Futures.immediateFuture((Final) okResponse());
        }
    }.times(1));

    long emitTime = System.currentTimeMillis();
    emitter.emit(new UnitEvent("test", 1));

    latch.await();
    long timeWaited = System.currentTimeMillis() - emitTime;
    Assert.assertTrue(String.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2),
            timeWaited < timeBetweenEmissions * 2);

    waitForEmission(emitter);

    final CountDownLatch thisLatch = new CountDownLatch(1);
    httpClient.setGoHandler(new GoHandler() {
        @Override
        public <Intermediate, Final> ListenableFuture<Final> go(Request intermediateFinalRequest,
                HttpResponseHandler<Intermediate, Final> handler) throws Exception {
            thisLatch.countDown();
            return Futures.immediateFuture((Final) okResponse());
        }
    }.times(1));

    emitTime = System.currentTimeMillis();
    emitter.emit(new UnitEvent("test", 2));

    thisLatch.await();
    timeWaited = System.currentTimeMillis() - emitTime;
    Assert.assertTrue(String.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2),
            timeWaited < timeBetweenEmissions * 2);

    waitForEmission(emitter);
    closeNoFlush(emitter);
    Assert.assertTrue("httpClient.succeeded()", httpClient.succeeded());
}

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

@Test
public void testGetVmsAsync() 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/*  ww w .ja v a  2s.  c  o  m*/
        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:com.vmware.photon.controller.api.client.resource.DeploymentRestApiTest.java

@Test
public void testGetVmsAsync() 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 DeploymentRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.getAllDeploymentVmsAsync("foo", new FutureCallback<ResourceList<Vm>>() {
        @Override/* ww w.  j ava2s  . co  m*/
        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:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java

@Test
public void testGetFabricNodeState() throws IOException, InterruptedException {
    final FabricNodeState mockResponse = new FabricNodeState();
    mockResponse.setState(com.vmware.photon.controller.nsxclient.datatypes.FabricNodeState.SUCCESS);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getFabricNodeState("nodeId",
            new com.google.common.util.concurrent.FutureCallback<FabricNodeState>() {
                @Override/*from  w w w  .  j a  v  a  2s. c o m*/
                public void onSuccess(FabricNodeState result) {
                    assertEquals(result, mockResponse);
                    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.couchbase.client.TestingClient.java

public HttpFuture<String> asyncHttpGet(String uri) throws UnsupportedEncodingException {
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout);

    HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);
    HttpOperationImpl op = new TestOperationImpl(request, new TestCallback() {
        private String json;

        @Override/*w w w  . j a va  2s .c o m*/
        public void receivedStatus(OperationStatus status) {
            crv.set(json, status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }

        @Override
        public void getData(String response) {
            json = response;
        }
    });
    crv.setOperation(op);
    addOp(op);
    return crv;
}

From source file:com.uphyca.kitkat.storage.internal.impl.LiveSdkSkyDriveClient.java

@Override
public void initializeIfNecessary() {
    if (mLiveConnectClient != null) {
        return;//from  w  w w  .  j av  a  2  s.c o m
    }
    final CountDownLatch lock = new CountDownLatch(1);
    mLiveAuthClient.initialize(SCOPES, new LiveAuthListener() {
        @Override
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            if (status == LiveStatus.CONNECTED) {
                mLiveConnectClient = new LiveConnectClient(session);
            }
            lock.countDown();
        }

        @Override
        public void onAuthError(LiveAuthException exception, Object userState) {
            lock.countDown();
        }
    });
    try {
        lock.await();
    } catch (InterruptedException ignore) {
    }
}

From source file:com.vladmihalcea.mongo.dao.ProductRepositoryIT.java

@Test
public void testRetries() throws InterruptedException {
    Product product = new Product();
    product.setId(123L);//from www. j a va 2  s. co  m
    product.setName("Tv");
    productRepository.save(product);
    Product savedProduct = productRepository.findOne(123L);
    assertEquals(savedProduct, product);

    final int threadsNumber = 10;

    final AtomicInteger atomicInteger = new AtomicInteger();
    final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1);
    final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1);

    for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) {
        final long index = (long) atomicInteger.get() * threadsNumber;
        LOGGER.info("Scheduling thread index {}", index);
        Thread testThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(123L, UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.error("Exception thrown!", e);
                } finally {
                    endLatch.countDown();
                }
            }
        });
        testThread.start();
    }
    startLatch.countDown();
    LOGGER.info("Waiting for threads to be done");
    endLatch.countDown();
    endLatch.await();
    LOGGER.info("Threads are done");
}