List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java
@Test public void testReleaseBrokenBarrier() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); SteppableThread latchStepper = new SteppableWaitForLatch(latch); interruptInWait(latchStepper, TestMode.RELEASE); try {//from www . j a v a 2 s.co m latchStepper.release(); Assert.fail(); } catch (RuntimeException e) { Assert.assertEquals(BrokenBarrierException.class, e.getCause().getClass()); } ((CyclicBarrier) ReflectionTestUtils.getField(latchStepper, "stepStart")).reset(); latchStepper.start(); latch.countDown(); latchStepper.releaseAndJoin(); }
From source file:org.duracloud.durastore.rest.ManifestRestTest.java
@Test public void generateAsync() throws Exception { String format = ManifestFormat.TSV.name(); CountDownLatch latch = new CountDownLatch(1); setupAccountId();/* ww w . j a va2s. c o m*/ expect(request.getAttribute(Constants.SERVER_HOST)).andReturn("host"); expect(request.getAttribute(Constants.SERVER_PORT)).andReturn(443); expect(request.getContextPath()).andReturn("/context"); expectGetManifest(format); StorageAccount sa = createMock("StorageAccount", StorageAccount.class); expect(sa.getId()).andReturn(storeId); expect(sa.getType()).andReturn(StorageProviderType.AMAZON_S3); expect(storageProviderFactory.getStorageAccounts()).andReturn(Arrays.asList(sa)); expect(storageProviderFactory.getStorageProvider()).andReturn(provider); Map<String, String> props = new HashMap<>(); props.put(HttpHeaders.CONTENT_ENCODING, "gzip"); expect(provider.addContent(isA(String.class), isA(String.class), eq(ManifestFormat.TSV.getMimeType()), eq(props), anyLong(), isA(String.class), isA(InputStream.class))).andAnswer(new IAnswer<String>() { @Override public String answer() throws Throwable { latch.countDown(); return "checksum"; } }); replayAll(); Response response = rest.generateManifest(spaceId, format, storeId); URI uri = (URI) response.getLocation(); assertEquals(HttpStatus.SC_ACCEPTED, response.getStatus()); assertNotNull(uri); assertTrue("async generate and upload did not complete", latch.await(10000, TimeUnit.MILLISECONDS)); }
From source file:ch.cyberduck.core.http.AbstractHttpWriteFeature.java
public HttpResponseOutputStream<T> write(final Path file, final TransferStatus status, final DelayedHttpEntityCallable<T> command, final DelayedHttpEntity entity) throws BackgroundException { // Signal on enter streaming final CountDownLatch entry = entity.getEntry(); final CountDownLatch exit = new CountDownLatch(1); try {/* ww w .j av a 2s. co m*/ if (StringUtils.isNotBlank(status.getMime())) { entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, status.getMime())); } else { entity.setContentType(MimeTypeService.DEFAULT_CONTENT_TYPE); } final FutureHttpResponse target = new FutureHttpResponse() { @Override public void run() { try { if (status.isCanceled()) { throw new ConnectionCanceledException(); } response = command.call(entity); } catch (BackgroundException 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(); } } }; final ThreadFactory factory = new NamedThreadFactory(String.format("http-%s", file.getName())); final Thread t = factory.newThread(target); t.start(); // Wait for output stream to become available entry.await(); if (null != target.getException()) { if (target.getException() instanceof BackgroundException) { throw (BackgroundException) target.getException(); } throw new DefaultExceptionMappingService().map(target.getException()); } final OutputStream stream = entity.getStream(); return new HttpResponseOutputStream<T>(stream) { @Override public void flush() throws IOException { stream.flush(); } /** * Only available after this stream is closed. * @return Response from server for upload */ @Override public T getStatus() throws BackgroundException { try { if (status.isCanceled()) { throw new ConnectionCanceledException(); } // Block the calling thread until after the full response from the server // has been consumed. exit.await(); } catch (InterruptedException e) { throw new DefaultExceptionMappingService().map(e); } if (null != target.getException()) { if (target.getException() instanceof BackgroundException) { throw (BackgroundException) target.getException(); } throw new DefaultExceptionMappingService().map(target.getException()); } return target.getResponse(); } }; } catch (InterruptedException e) { log.warn(String.format("Error waiting for output stream for %s", file)); throw new DefaultExceptionMappingService().map(e); } }
From source file:com.fusesource.forge.jmstest.executor.AbstractBenchmarkExecutionContainer.java
public void run() { init();/*w w w . j a va 2 s . c o m*/ log().info("Benchmark framework has started..."); latch = new CountDownLatch(1); execute(); try { latch.await(); } catch (InterruptedException e) { // ignore } release(); ReleaseManager.getInstance().deregister(this); log().info("Done Benchmarking framework"); }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphoreCluster.java
@Test public void testKilledServerWithEnsembleProvider() throws Exception { final int CLIENT_QTY = 10; final Timing timing = new Timing(); final String PATH = "/foo/bar/lock"; ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY); ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService); TestingCluster cluster = new TestingCluster(3); try {// w ww.j a v a 2 s. c o m cluster.start(); final AtomicReference<String> connectionString = new AtomicReference<String>( cluster.getConnectString()); final EnsembleProvider provider = new EnsembleProvider() { @Override public void start() throws Exception { } @Override public String getConnectionString() { return connectionString.get(); } @Override public void close() throws IOException { } }; final Semaphore acquiredSemaphore = new Semaphore(0); final AtomicInteger acquireCount = new AtomicInteger(0); final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY); for (int i = 0; i < CLIENT_QTY; ++i) { completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.builder().ensembleProvider(provider) .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()) .retryPolicy(new ExponentialBackoffRetry(100, 3)).build(); try { final Semaphore suspendedSemaphore = new Semaphore(0); client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST)) { suspendedLatch.countDown(); suspendedSemaphore.release(); } } }); client.start(); InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1); while (!Thread.currentThread().isInterrupted()) { Lease lease = null; try { lease = semaphore.acquire(); acquiredSemaphore.release(); acquireCount.incrementAndGet(); suspendedSemaphore.acquire(); } catch (Exception e) { // just retry } finally { if (lease != null) { acquireCount.decrementAndGet(); IOUtils.closeQuietly(lease); } } } } finally { IOUtils.closeQuietly(client); } return null; } }); } Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore)); Assert.assertEquals(1, acquireCount.get()); cluster.close(); timing.awaitLatch(suspendedLatch); timing.forWaiting().sleepABit(); Assert.assertEquals(0, acquireCount.get()); cluster = new TestingCluster(3); cluster.start(); connectionString.set(cluster.getConnectString()); timing.forWaiting().sleepABit(); Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore)); timing.forWaiting().sleepABit(); Assert.assertEquals(1, acquireCount.get()); } finally { executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); executorService.shutdownNow(); IOUtils.closeQuietly(cluster); } }
From source file:com.balch.mocktrade.finance.FinanceYQLModel.java
@Override public void getQuotes(final List<String> symbols, final RequestListener<Map<String, Quote>> listener) { final CountDownLatch latch = new CountDownLatch(2); final Map<String, Quote> yqlQuotes = new HashMap<String, Quote>(); final Map<String, Quote> googleQuotes = new HashMap<String, Quote>(); final StringBuilder errorMessages = new StringBuilder(); this.getYQLQuotes(symbols, new RequestListener<Map<String, Quote>>() { @Override//from w ww . j a v a 2 s . c o m public void onResponse(Map<String, Quote> response) { try { yqlQuotes.putAll(response); } finally { latch.countDown(); } } @Override public void onErrorResponse(String error) { errorMessages.append(error).append("\n"); latch.countDown(); } }); this.getGoogleRealTimeQuotes(symbols, new RequestListener<Map<String, Quote>>() { @Override public void onResponse(Map<String, Quote> response) { try { googleQuotes.putAll(response); } finally { latch.countDown(); } } @Override public void onErrorResponse(String error) { errorMessages.append(error).append("\n"); latch.countDown(); } }); try { // wait for both requests to finish latch.await(); if (errorMessages.length() == 0) { // add google's realtime quotes on top of yql quotes for (Quote q : googleQuotes.values()) { Quote yqlQuote = yqlQuotes.get(q.getSymbol()); if (yqlQuote != null) { yqlQuote.setPrice(q.getPrice()); yqlQuote.setLastTradeTime(q.getLastTradeTime()); } else { Log.wtf(TAG, "GoogleQuote contains a symbol that is not in the yqlQuote map. GoogleQuote Symbol:" + q.getSymbol() + " Submitted Symbols:" + TextUtils.join(",", symbols)); } } listener.onResponse(yqlQuotes); } else { listener.onErrorResponse(errorMessages.toString()); } } catch (InterruptedException e) { } }
From source file:com.contentful.vaultintegration.BaseTest.java
protected void sync(SyncConfig config) throws InterruptedException { if (config == null) { config = SyncConfig.builder().setClient(client).build(); }// w w w . ja v a 2 s . co m final CountDownLatch latch = new CountDownLatch(1); Executor executor = new Executor() { @Override public void execute(Runnable command) { command.run(); } }; final SyncResult[] result = { null }; SyncCallback callback = new SyncCallback() { @Override public void onResult(SyncResult r) { result[0] = r; latch.countDown(); } }; vault.requestSync(config, callback, executor); latch.await(); assertThat(result[0]).isNotNull(); if (!result[0].isSuccessful()) { throw (RuntimeException) result[0].error(); } }
From source file:com.fusesource.forge.jmstest.threading.LimitedTimeScheduledExecutor.java
public void run() { log().info(getClass().getSimpleName() + " " + getName() + " starting."); getReleaseManager().register(this); executor = new ScheduledThreadPoolExecutor(1); executor.scheduleAtFixedRate(getTask(), 0, getInterval(), TimeUnit.SECONDS); latch = new CountDownLatch(1); new ScheduledThreadPoolExecutor(1).schedule(new Runnable() { public void run() { try { release();//from w w w .j a v a 2 s.co m } catch (Exception e) { } } }, duration, TimeUnit.SECONDS); try { latch.await(); } catch (InterruptedException ie) { try { release(); } catch (Exception e) { } } isRunning = false; log().info(getClass().getSimpleName() + " " + getName() + " finished."); }
From source file:com.netflix.curator.framework.imps.TestFrameworkBackground.java
@Test public void testBasic() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try {/* w ww . j ava 2 s .c o m*/ client.start(); final CountDownLatch latch = new CountDownLatch(3); final List<String> paths = Lists.newArrayList(); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { paths.add(event.getPath()); latch.countDown(); } }; client.create().inBackground(callback).forPath("/one"); client.create().inBackground(callback).forPath("/one/two"); client.create().inBackground(callback).forPath("/one/two/three"); latch.await(); Assert.assertEquals(paths, Arrays.asList("/one", "/one/two", "/one/two/three")); } finally { IOUtils.closeQuietly(client); } }
From source file:org.cometd.client.JacksonCustomSerializationTest.java
@Test public void testJacksonCustomSerialization() throws Exception { Map<String, String> serverOptions = new HashMap<>(); serverOptions.put(AbstractServerTransport.JSON_CONTEXT_OPTION, jacksonContextServerClassName); serverOptions.put(AbstractHttpTransport.JSON_DEBUG_OPTION, "true"); Map<String, Object> clientOptions = new HashMap<>(); clientOptions.put(ClientTransport.JSON_CONTEXT_OPTION, jacksonContextClientClassName); startServer(serverOptions);/*from w w w . ja v a 2 s .c o m*/ String channelName = "/data"; final String dataContent = "random"; final long extraContent = 13; final CountDownLatch latch = new CountDownLatch(1); LocalSession service = bayeux.newLocalSession("custom_serialization"); service.handshake(); service.getChannel(channelName).subscribe(new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { Data data = (Data) message.getData(); Assert.assertEquals(dataContent, data.content); Map<String, Object> ext = message.getExt(); Assert.assertNotNull(ext); Extra extra = (Extra) ext.get("extra"); Assert.assertEquals(extraContent, extra.content); latch.countDown(); } }); BayeuxClient client = new BayeuxClient(cometdURL, new LongPollingTransport(clientOptions, httpClient)); client.addExtension(new ExtraExtension(extraContent)); client.handshake(); Assert.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED)); // Wait for the connect to establish Thread.sleep(1000); client.getChannel(channelName).publish(new Data(dataContent)); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); disconnectBayeuxClient(client); }