List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:com.fusesource.forge.jmstest.frontend.CommandLineClientTest.java
@Test public void testRunWithAbsoluteConfigLocation() throws InterruptedException { File benchmarkDir = JmsTesterUtils.getResourceAsFile("/simple"); assertTrue(benchmarkDir.isDirectory()); final CountDownLatch testPassedLatch = new CountDownLatch(1); SimpleTestExecutionContainer container = new SimpleTestExecutionContainer() { @Override/*from w w w . ja va 2 s.c o m*/ protected BenchmarkCommandHandler createTestHandler() { return new DefaultCommandHandler() { public boolean handleCommand(BenchmarkCommand command) { if (command.getCommandType() == CommandTypes.SUBMIT_BENCHMARK) { testPassedLatch.countDown(); return true; } return false; } }; } }; container.start(); // exercise unit commandLineClient.run(new String[] { "-command", "submit:" + benchmarkDir.getAbsolutePath() }); assertTrue("CommandLineClient did not send a SUBMIT_BENCHMARK command", testPassedLatch.await(1, TimeUnit.SECONDS)); container.stop(); }
From source file:org.killbill.queue.DefaultQueueLifecycle.java
@Override public boolean startQueue() { if (config.isProcessingOff() || !isStarted.compareAndSet(false, true)) { return false; }/*w w w.jav a 2s . co m*/ isProcessingEvents = true; curActiveThreads = 0; final DefaultQueueLifecycle thePersistentQ = this; final CountDownLatch doneInitialization = new CountDownLatch(nbThreads); log.info(String.format("%s: Starting with %d threads", svcQName, nbThreads)); for (int i = 0; i < nbThreads; i++) { executor.execute(new Runnable() { @Override public void run() { log.info(String.format("%s: Thread %s [%d] starting", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId())); synchronized (thePersistentQ) { curActiveThreads++; } doneInitialization.countDown(); try { while (true) { if (!isProcessingEvents) { break; } final long beforeLoop = System.nanoTime(); try { if (!isProcessingSuspended.get()) { doProcessEvents(); } } catch (Exception e) { log.warn(String.format( "%s: Thread %s [%d] got an exception, catching and moving on...", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId()), e); } finally { final long afterLoop = System.nanoTime(); sleepALittle((afterLoop - beforeLoop) / ONE_MILLION); } } } catch (InterruptedException e) { log.info(String.format("%s: Thread %s got interrupted, exting... ", svcQName, Thread.currentThread().getName())); } catch (Throwable e) { log.error(String.format("%s: Thread %s got an exception, exting... ", svcQName, Thread.currentThread().getName()), e); } finally { log.info(String.format("%s: Thread %s has exited", svcQName, Thread.currentThread().getName())); synchronized (thePersistentQ) { curActiveThreads--; thePersistentQ.notify(); } } } private void sleepALittle(long loopTimeMsec) throws InterruptedException { final long remainingSleepTime = config.getSleepTimeMs() - loopTimeMsec; if (remainingSleepTime > 0) { Thread.sleep(remainingSleepTime); } } }); } try { final boolean success = doneInitialization.await(waitTimeoutMs, TimeUnit.MILLISECONDS); if (!success) { log.warn(String.format("%s: Failed to wait for all threads to be started, got %d/%d", svcQName, (nbThreads - doneInitialization.getCount()), nbThreads)); } else { log.info(String.format("%s: Done waiting for all threads to be started, got %d/%d", svcQName, (nbThreads - doneInitialization.getCount()), nbThreads)); } } catch (InterruptedException e) { log.warn(String.format("%s: Start sequence, got interrupted", svcQName)); } return true; }
From source file:gobblin.compliance.validation.ComplianceValidationJob.java
public void run() throws IOException { Preconditions.checkNotNull(this.finder, "Dataset finder class is not set"); List<Dataset> datasets = this.finder.findDatasets(); this.finishCleanSignal = Optional.of(new CountDownLatch(datasets.size())); for (final Dataset dataset : datasets) { ListenableFuture<Void> future = this.service.submit(new Callable<Void>() { @Override// w w w. ja v a2 s. com public Void call() throws Exception { if (dataset instanceof ValidatableDataset) { ((ValidatableDataset) dataset).validate(); } else { log.warn("Not an instance of " + ValidatableDataset.class + " Dataset won't be validated " + dataset.datasetURN()); } return null; } }); Futures.addCallback(future, new FutureCallback<Void>() { @Override public void onSuccess(@Nullable Void result) { ComplianceValidationJob.this.finishCleanSignal.get().countDown(); log.info("Successfully validated: " + dataset.datasetURN()); } @Override public void onFailure(Throwable t) { ComplianceValidationJob.this.finishCleanSignal.get().countDown(); log.warn("Exception caught when validating " + dataset.datasetURN() + ".", t); ComplianceValidationJob.this.throwables.add(t); ComplianceValidationJob.this.eventSubmitter.submit( ComplianceEvents.Validation.FAILED_EVENT_NAME, ImmutableMap.of(ComplianceEvents.FAILURE_CONTEXT_METADATA_KEY, ExceptionUtils.getFullStackTrace(t), ComplianceEvents.DATASET_URN_METADATA_KEY, dataset.datasetURN())); } }); } }
From source file:org.kitodo.data.index.elasticsearch.RestClientImplementation.java
/** * Add list of documents to the index. This method will be used for add whole table to the index. * It performs asynchronous request.//w ww . j a v a 2 s. c o m * * @param documentsToIndex list of json documents to the index */ public String addType(HashMap<Integer, HttpEntity> documentsToIndex) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(documentsToIndex.size()); final StringBuilder output = new StringBuilder(); for (HashMap.Entry<Integer, HttpEntity> entry : documentsToIndex.entrySet()) { restClient.performRequestAsync("PUT", "/" + this.getIndex() + "/" + this.getType() + "/" + entry.getKey(), Collections.<String, String>emptyMap(), entry.getValue(), new ResponseListener() { @Override //problem with return type - it should be String //dirty hack private variable ArrayResult public void onSuccess(Response response) { output.append(response.toString()); latch.countDown(); } @Override public void onFailure(Exception exception) { latch.countDown(); } }); } latch.await(); return output.toString(); }
From source file:org.smartfrog.services.anubis.Node.java
public Node(AnnotationConfigApplicationContext context, int c, CountDownLatch launchLatch, CountDownLatch startLatch, CountDownLatch endLatch, int maxSleep, int messageCount) throws Exception { this.context = context; cardinality = c;/* w ww. j a v a2 s.c o m*/ this.launchLatch = launchLatch; this.startLatch = startLatch; this.endLatch = endLatch; this.maxSleep = maxSleep; messagesToSend = messageCount; for (int i = 0; i < cardinality; i++) { receiveHistory.put(i, new CopyOnWriteArrayList<ValueHistory>()); msgReceivedLatches.put(i, new CountDownLatch(messageCount)); } identity = context.getBean(Identity.class).id; partition = context.getBean(Partition.class); partition.register(new PartitionNotification() { @Override public void objectNotification(Object obj, int sender, long time) { receiveHistory.get(sender).add(new ValueHistory(sender, obj, time, Action.NEW)); msgReceivedLatches.get(sender).countDown(); } @Override public void partitionNotification(View view, int leader) { Node.this.view = view; if (view.isStable() && view.cardinality() == cardinality) { // System.out.println("Launching: " + view + " : " + instance); Node.this.launchLatch.countDown(); } else { // System.out.println("Not launching: " + view + " : " + instance); } } }); }
From source file:org.jboss.aerogear.test.api.sender.SenderRequest.java
public SenderRequest send(UnifiedMessage message, String pushApplicationId, String masterSecret) { DefaultPushSender.Builder senderBuilder = DefaultPushSender .withRootServerURL(getSession().getBaseUrl().toExternalForm()).pushApplicationId(pushApplicationId) .masterSecret(masterSecret); if (customTrustStorePath != null) { senderBuilder.customTrustStore(customTrustStorePath, customTrustStoreType, customTrustStorePassword); }/*w w w . j av a 2s .com*/ PushSender senderClient = senderBuilder.build(); final CountDownLatch latch = new CountDownLatch(1); MessageResponseCallback callback = new MessageResponseCallback() { @Override public void onComplete() { latch.countDown(); } }; try { // The send is synchronous for now but I left the latch.await there in case the send becomes async again. senderClient.send(message, callback); latch.await(5000, TimeUnit.MILLISECONDS); } catch (PushSenderHttpException exception) { // In case we get the exception, we will assert it UnexpectedResponseException.verifyStatusCode(exception.getStatusCode(), HttpStatus.SC_ACCEPTED); } catch (InterruptedException e) { e.printStackTrace(); } return this; }
From source file:example.springdata.cassandra.people.ReactivePersonRepositoryIntegrationTest.java
/** * Result set {@link com.datastax.driver.core.Row}s are converted to entities as they are emitted. Reactive pull and * prefetch define the amount of fetched records. *//*w ww.j ava 2s . c o m*/ @Test public void shouldPerformConversionBeforeResultProcessing() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); repository.findAll() // .doOnNext(System.out::println) // .doOnComplete(countDownLatch::countDown) // .doOnError(throwable -> countDownLatch.countDown()) // .subscribe(); countDownLatch.await(); }
From source file:byps.test.TestRemoteServerR.java
public void testSimultan() throws InterruptedException { Executor tpool = Executors.newCachedThreadPool(); int nbOfThreads = 5; final CountDownLatch cdl = new CountDownLatch(nbOfThreads); for (int t = 0; t < nbOfThreads; t++) { Runnable run = new Runnable() { public void run() { TestRemoteServerR testObj = new TestRemoteServerR(); try { testObj.testLoop10(); } catch (Throwable e) { log.error("exception", e); } finally { cdl.countDown();/*from w ww .j ava2s . c o m*/ } } }; tpool.execute(run); } cdl.await(); }
From source file:my.adam.smo.client.Client.java
public BlockingRpcChannel blockingConnect(final InetSocketAddress sa) { return new BlockingRpcChannel() { private int countDownCallTimesToRelease = 1; private RpcChannel rpc = connect(sa); @Override// w w w. j a va 2 s . c om public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request, Message responsePrototype) throws ServiceException { StopWatch stopWatch = new StopWatch("callBlockingMethod"); stopWatch.start(); final CountDownLatch callbackLatch = new CountDownLatch(countDownCallTimesToRelease); final AtomicReference<Message> result = new AtomicReference<Message>(); RpcCallback<Message> done = new RpcCallback<Message>() { @Override public void run(Message parameter) { result.set(parameter); callbackLatch.countDown(); } }; rpc.callMethod(method, controller, request, responsePrototype, done); try { boolean succeededBeforeTimeout = callbackLatch.await(blocking_method_call_timeout, TimeUnit.SECONDS); if (!succeededBeforeTimeout) { throw new ServiceException( "blocking method timeout reached for method:" + method.getFullName()); } } catch (InterruptedException e) { getLogger().error("call failed", e); stopWatch.stop(); } stopWatch.stop(); getLogger().trace(stopWatch.shortSummary()); return result.get(); } }; }
From source file:reactor.ipc.netty.tcp.TcpServerTests.java
@Test public void tcpServerHandlesJsonPojosOverSsl() throws Exception { final CountDownLatch latch = new CountDownLatch(2); SslContext clientOptions = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();/*w w w. java 2 s.c o m*/ final TcpServer server = TcpServer.create(opts -> opts.listen("localhost").sslSelfSigned()); ObjectMapper m = new ObjectMapper(); NettyContext connectedServer = server.newHandler((in, out) -> { in.receive().asByteArray().map(bb -> { try { return m.readValue(bb, Pojo.class); } catch (IOException io) { throw Exceptions.propagate(io); } }).log("conn").subscribe(data -> { if ("John Doe".equals(data.getName())) { latch.countDown(); } }); return out.sendString(Mono.just("Hi")).neverComplete(); }).block(Duration.ofSeconds(30)); final TcpClient client = TcpClient.create( opts -> opts.connect("localhost", connectedServer.address().getPort()).sslContext(clientOptions)); NettyContext connectedClient = client.newHandler((in, out) -> { //in in.receive().asString().log("receive").subscribe(data -> { if (data.equals("Hi")) { latch.countDown(); } }); //out return out.send(Flux.just(new Pojo("John" + " Doe")).map(s -> { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { m.writeValue(os, s); return out.alloc().buffer().writeBytes(os.toByteArray()); } catch (IOException ioe) { throw Exceptions.propagate(ioe); } })).neverComplete(); // return Mono.empty(); }).block(Duration.ofSeconds(30)); assertTrue("Latch was counted down", latch.await(5, TimeUnit.SECONDS)); connectedClient.dispose(); connectedServer.dispose(); }