List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:example.springdata.mongodb.people.ReactivePersonRepositoryIntegrationTest.java
/** * This sample performs a count, inserts data and performs a count again using reactive operator chaining. *//*w ww.ja v a2 s.co m*/ @Test public void shouldInsertAndCountData() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); repository.count() // .doOnNext(System.out::println) // .thenMany(repository.saveAll(Flux.just(new Person("Hank", "Schrader", 43), // new Person("Mike", "Ehrmantraut", 62)))) // .last() // .flatMap(v -> repository.count()) // .doOnNext(System.out::println) // .doOnSuccess(it -> countDownLatch.countDown()) // .doOnError(throwable -> countDownLatch.countDown()) // .subscribe(); countDownLatch.await(); }
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 va2s . 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:hudson.plugins.mercurial.MercurialContainer.java
@SuppressWarnings("deprecation") public Slave createSlave(JenkinsRule r) throws Exception { DumbSlave slave = new DumbSlave("slave" + r.jenkins.getNodes().size(), "dummy", "/home/test/slave", "1", Node.Mode.NORMAL, "mercurial", new SSHLauncher(ipBound(22), port(22), "test", "test", "", ""), RetentionStrategy.INSTANCE, Collections.<NodeProperty<?>>emptyList()); r.jenkins.addNode(slave);// www . j ava 2s . co m // Copied from JenkinsRule: final CountDownLatch latch = new CountDownLatch(1); ComputerListener waiter = new ComputerListener() { @Override public void onOnline(Computer C, TaskListener t) { latch.countDown(); unregister(); } }; waiter.register(); latch.await(); return slave; }
From source file:com.microsoft.office.integration.test.ContactsAsyncTestCase.java
public void testUpdate() { counter = new CountDownLatch(1); // create contact first prepareContact();// w w w. j a va2 s . co m Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { public void onFailure(Throwable t) { reportError(t); counter.countDown(); } public void onSuccess(Void result) { try { updateAndCheck(); // clean up removeContact(); } catch (Throwable t) { reportError(t); } counter.countDown(); }; }); try { if (!counter.await(60000, TimeUnit.MILLISECONDS)) { fail("testUpdate() timed out"); } } catch (InterruptedException e) { fail("testUpdate() has been interrupted"); } }
From source file:ch.cyberduck.core.http.HttpPath.java
/** * @param command Callable writing entity to stream and returning checksum * @param <T> Type of returned checksum * @return Outputstream to write entity into. * @throws IOException Transport error/*from w w w . ja v a 2 s. com*/ */ protected <T> ResponseOutputStream<T> write(final DelayedHttpEntityCallable<T> command) throws IOException { /** * Signal on enter streaming */ final CountDownLatch entry = new CountDownLatch(1); final CountDownLatch exit = new CountDownLatch(1); try { final DelayedHttpEntity entity = new DelayedHttpEntity(entry) { @Override public long getContentLength() { return command.getContentLength(); } }; final String type = new MappingMimeTypeService().getMime(this.getName()); entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, type)); final FutureHttpResponse<T> target = new FutureHttpResponse<T>() { @Override public void run() { // Need batcher for logging messages up to the interface final ActionOperationBatcher autorelease = ActionOperationBatcherFactory.get(); try { response = command.call(entity); } catch (IOException e) { exception = e; } finally { // For zero byte files #writeTo is never called and the entry latch not triggered entry.countDown(); // Continue reading the response exit.countDown(); autorelease.operate(); } } }; final Thread t = factory.newThread(target); t.start(); // Wait for output stream to become available entry.await(); if (null != target.getException()) { throw target.getException(); } final OutputStream stream = entity.getStream(); return new ResponseOutputStream<T>(stream) { /** * Only available after this stream is closed. * @return Response from server for upload * @throws IOException Transport error */ @Override public T getResponse() throws IOException { try { // Block the calling thread until after the full response from the server // has been consumed. exit.await(); } catch (InterruptedException e) { IOException failure = new IOException(e.getMessage()); failure.initCause(e); throw failure; } if (null != target.getException()) { throw target.getException(); } return target.getResponse(); } }; } catch (InterruptedException e) { log.error("Error waiting for output stream:" + e.getMessage()); IOException failure = new IOException(e.getMessage()); failure.initCause(e); throw failure; } }
From source file:com.microsoft.office.core.AttachmentsAsyncTestCase.java
@Test(timeout = 60000) public void createFileAttachmentTest() throws Exception { counter = new CountDownLatch(1); final IFileAttachment attachment = createFileAttachment(); Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { @Override/* ww w. j av a2 s. co m*/ public void onSuccess(Void res) { checkCreated(attachment); try { removeAttachment(attachment); } catch (Exception e) { reportError(e); } counter.countDown(); } @Override public void onFailure(Throwable err) { reportError(err); } }); counter.await(); }
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 {// ww w . ja va 2 s . c om 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:org.eclipse.hono.adapter.VertxBasedAdapterApplication.java
@PostConstruct public void registerVerticles() { if (running.compareAndSet(false, true)) { final int instanceCount = honoConfig.getMaxInstances(); try {/*from www . ja va 2s .com*/ final CountDownLatch latch = new CountDownLatch(1); final Future<Void> startFuture = Future.future(); startFuture.setHandler(done -> { if (done.succeeded()) { latch.countDown(); } else { LOG.error("could not start '{}' adapter", this.getName(), done.cause()); } }); deployVerticle(instanceCount, startFuture); if (latch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) { LOG.info("'{}' adapter startup completed successfully", this.getName()); } else { LOG.error("startup timed out after {} seconds, shutting down ...", honoConfig.getStartupTimeout()); shutdown(); } } catch (InterruptedException e) { LOG.error("startup process has been interrupted, shutting down ..."); Thread.currentThread().interrupt(); shutdown(); } } }
From source file:com.netflix.curator.framework.imps.TestFrameworkEdges.java
@Test public void testReconnectAfterLoss() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try {//w w w.jav a2 s.c om client.start(); final CountDownLatch lostLatch = new CountDownLatch(1); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.LOST) { lostLatch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); client.checkExists().forPath("/"); server.close(); Assert.assertTrue(timing.awaitLatch(lostLatch)); try { client.checkExists().forPath("/"); Assert.fail(); } catch (KeeperException.ConnectionLossException e) { // correct } server = new TestingServer(server.getPort()); client.checkExists().forPath("/"); } finally { IOUtils.closeQuietly(client); } }