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.DeploymentApiTest.java

@Test
public void testListAllAsync() throws Exception {
    Deployment deployment = getNewDeployment();

    ResourceList<Deployment> deploymentResourceList = new ResourceList<>(Arrays.asList(deployment));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(deploymentResourceList);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    DeploymentApi deploymentApi = new DeploymentApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.listAllAsync(new FutureCallback<ResourceList<Deployment>>() {
        @Override/*  ww  w .  j  a v  a2 s  .  c o m*/
        public void onSuccess(@Nullable ResourceList<Deployment> result) {
            assertEquals(result.getItems(), deploymentResourceList.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 testListAllAsync() throws Exception {
    Deployment deployment = getNewDeployment();

    ResourceList<Deployment> deploymentResourceList = new ResourceList<>(Arrays.asList(deployment));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(deploymentResourceList);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    DeploymentApi deploymentApi = new DeploymentRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.listAllAsync(new FutureCallback<ResourceList<Deployment>>() {
        @Override//from  w  ww .ja  va 2s  .  c o m
        public void onSuccess(@Nullable ResourceList<Deployment> result) {
            assertEquals(result.getItems(), deploymentResourceList.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.microsoft.office.core.FolderAsyncTestCase.java

@Test
public void moveAndCopyTest() throws Exception {
    final String name = "move and copy test" + (int) (Math.random() * 1000000);
    counter = new CountDownLatch(1);

    Futures.addCallback(Me.getRootFolderAsync().get().getChildFoldersAsync(), new FutureCallback<IFolders>() {
        @Override/* ww  w . j a v  a  2  s. c  o  m*/
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        @Override
        public void onSuccess(IFolders result) {
            try {
                FolderAsyncTestCase.this.folder = result.newFolder();
                FolderAsyncTestCase.this.folder.setDisplayName(name);
                FolderAsyncTestCase.this.folder = FolderAsyncTestCase.this.folder
                        .moveAsync(Me.getDraftsAsync().get().getId()).get();
                final CountDownLatch cdl = new CountDownLatch(1);
                Futures.addCallback(FolderAsyncTestCase.this.folder.copyAsync(Me.getRootFolder().getId()),
                        new FutureCallback<IFolder>() {
                            @Override
                            public void onFailure(Throwable t) {
                                reportError(t);
                                cdl.countDown();
                            }

                            @Override
                            public void onSuccess(IFolder copied) {
                                try {
                                    Me.getFolders().delete(FolderAsyncTestCase.this.folder.getId());
                                    if (copied != null) {
                                        Me.getFolders().delete(copied.getId());
                                    }

                                    Me.flush();
                                } catch (Throwable t) {
                                    reportError(t);
                                }

                                cdl.countDown();
                            }
                        });
                cdl.await();
            } catch (Throwable t) {
                reportError(t);
            }
            counter.countDown();
        }
    });
    counter.await();
}

From source file:org.kurento.repository.OneRecordingServer.java

private void prepareToUploadVideo(RepositoryItem repositoryItem) throws InterruptedException {

    RepositoryHttpRecorder recorder = repositoryItem.createRepositoryHttpRecorder("video-upload");

    log.info("The video must be uploaded with PUT or POST to the URL: " + recorder.getURL());

    readyToUploadWatch.countDown();/*from   w ww. ja v a2s  .c om*/

    recorder.setAutoTerminationTimeout(5 * 1000);
    log.info(
            "The recorder will be auto-terminated 5 seconds after the last uploading of content (http PUT or POST)");

    final CountDownLatch terminatedLatch = new CountDownLatch(1);

    recorder.addSessionStartedListener(new RepositoryHttpEventListener<HttpSessionStartedEvent>() {
        @Override
        public void onEvent(HttpSessionStartedEvent event) {
            log.info("Uploading started");
        }
    });

    recorder.addSessionTerminatedListener(new RepositoryHttpEventListener<HttpSessionTerminatedEvent>() {
        @Override
        public void onEvent(HttpSessionTerminatedEvent event) {
            log.info("Uploading terminated");
            terminatedLatch.countDown();
        }
    });

    terminatedLatch.await();
}

From source file:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java

@Test
public void testCreateTransportNode() throws IOException, InterruptedException {
    final TransportNode mockResponse = new TransportNode();
    mockResponse.setId("id");
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_CREATED);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.createTransportNode(new TransportNodeCreateSpec(),
            new com.google.common.util.concurrent.FutureCallback<TransportNode>() {
                @Override//from  ww w .  ja  v  a 2s  .  co m
                public void onSuccess(TransportNode 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.vmware.photon.controller.nsxclient.apis.FabricApiTest.java

@Test
public void testCreateTransportZone() throws IOException, InterruptedException {
    final TransportZone mockResponse = new TransportZone();
    mockResponse.setId("id");
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_CREATED);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.createTransportZone(new TransportZoneCreateSpec(),
            new com.google.common.util.concurrent.FutureCallback<TransportZone>() {
                @Override/*from w  w w .ja va2 s  .co m*/
                public void onSuccess(TransportZone 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.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void testWaitingProcessKilledServer() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    try {/*from w  w w . j  a  v a2 s  . c  o  m*/
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);

        final AtomicBoolean isFirst = new AtomicBoolean(true);
        ExecutorCompletionService<Object> service = new ExecutorCompletionService<Object>(
                Executors.newFixedThreadPool(2));
        for (int i = 0; i < 2; ++i) {
            service.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    InterProcessLock lock = makeLock(client);
                    lock.acquire();
                    try {
                        if (isFirst.compareAndSet(true, false)) {
                            timing.sleepABit();

                            server.stop();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            server = new TestingServer(server.getPort(), server.getTempDirectory());
                        }
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            // ignore
                        }
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < 2; ++i) {
            service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.googlecode.ehcache.annotations.integration.RefreshingSelfPopulatingTest.java

/**
 * Verify that setting selfPopulating=true will guarantee only 1 invocation
 * of the cached method.//w w w. java  2  s  .  co m
 * 
 * @throws Exception
 */
@Test //(timeout=1000)
public void testSelfPopulatingTrue() throws Exception {
    final CountDownLatch threadRunningLatch = new CountDownLatch(2);
    final CyclicBarrier proceedLatch = new CyclicBarrier(2);
    this.refreshingSelfPopulatingTestInterface.setThreadRunningLatch(threadRunningLatch);
    this.refreshingSelfPopulatingTestInterface.setProccedLatch(proceedLatch);

    Assert.assertEquals(0, this.refreshingSelfPopulatingTestInterface.getBlockingAInvocationCount());

    final ThreadGroupRunner threadGroup = new ThreadGroupRunner("testSelfPopulatingTrue-", true);

    threadGroup.addTask(1, new Runnable() {
        public void run() {
            threadRunningLatch.countDown();
            logger.trace("Calling blockingA(test2)");
            refreshingSelfPopulatingTestInterface.blockingA("test2");
        }
    });

    threadGroup.start();

    // wait for both threads to get going
    logger.trace("Waiting for threads to start");
    threadRunningLatch.await();

    // Let both threads complete
    logger.trace("Signal threads to proceed");
    proceedLatch.await();

    logger.trace("Waiting for threads to complete");
    threadGroup.join();

    // verify only 1 call between method A and method B
    Assert.assertEquals(1, this.refreshingSelfPopulatingTestInterface.getBlockingAInvocationCount());

    Thread.sleep(1500);
    proceedLatch.await();

    //Wait for the refresh thread to complete
    Thread.sleep(10);

    Assert.assertEquals(2, this.refreshingSelfPopulatingTestInterface.getBlockingAInvocationCount());

}

From source file:com.bj58.spat.gaea.server.util.async.AsyncWorker.java

private void execTimeoutTask() {
    try {/* w w  w.j  a  v  a  2 s.  c  om*/
        final AsyncTask task = taskQueue.take();
        if (task != null) {
            if ((System.currentTimeMillis() - task.getAddTime()) > task.getQtimeout()) {
                task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                return;
            } else {
                final CountDownLatch cdl = new CountDownLatch(1);
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Object obj = task.getHandler().run();
                            task.getHandler().messageReceived(obj);
                        } catch (Throwable ex) {
                            task.getHandler().exceptionCaught(ex);
                        } finally {
                            cdl.countDown();
                        }
                    }
                });
                cdl.await(getTimeout(task.getTimeout(), taskQueue.size()), TimeUnit.MILLISECONDS);
                if (cdl.getCount() > 0) {
                    task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                }
            }
        } else {
            logger.error("execTimeoutTask take task is null");
        }
    } catch (InterruptedException ie) {
        logger.error("");
    } catch (Throwable e) {
        logger.error("get task from poll error", e);
    }
}

From source file:com.couchbase.client.ViewNodeTest.java

private HttpOperation createHttpOperation() {
    View view = new View("a", "b", "c", true, true);
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<ViewResponse> crv = new HttpFuture<ViewResponse>(couchLatch, 60000);
    final HttpRequest request = new BasicHttpRequest("GET", "/pools", HttpVersion.HTTP_1_1);
    return new NoDocsOperationImpl(request, view, new ViewOperation.ViewCallback() {
        private ViewResponse vr = null;

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

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

        @Override
        public void gotData(ViewResponse response) {
            vr = response;
        }
    });
}