@Test public void unsubscribeAllTest() throws InterruptedException { Key k1 = Key.wrap("key1"); Key k2 = Key.wrap("key2"); Key k3 = Key.wrap("_key3"); final CountDownLatch latch = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(1); firehose.on( k1, (i) -> { latch.countDown(); }); firehose.on( k2, (i) -> { latch.countDown(); }); firehose.on( k3, (i) -> { latch2.countDown(); }); firehose.unregister(k -> ((String) k.getPart(0)).startsWith("key")); firehose.notify(k1, 1); firehose.notify(k2, 1); firehose.notify(k3, 1); assertThat(latch2.getCount(), is(0L)); assertThat(latch.getCount(), is(2L)); }
@Ensures({ "activeThreads.size() <= old(activeThreads.size())", "! activeThreads.contains(thread)", "countDownLatch.getCount() <= old(countDownLatch.getCount())" }) @Override public synchronized void threadIsDone(final Thread thread) { nThreadsAnalyzed++; if (DEBUG) logger.warn( " Countdown " + countDownLatch.getCount() + " in thread " + Thread.currentThread().getName()); super.threadIsDone(thread); // remove the thread from the list of active activeThreads, if it's in there, and decrement the // countdown latch if (activeThreads.remove(thread)) { // one less thread is live for those blocking on all activeThreads to be complete countDownLatch.countDown(); if (DEBUG) logger.warn( " -> Countdown " + countDownLatch.getCount() + " in thread " + Thread.currentThread().getName()); } }
@Override public void preGetOp( final ObserverContext<RegionCoprocessorEnvironment> e, final Get get, final List<Cell> results) throws IOException { if (e.getEnvironment().getRegion().getRegionInfo().getReplicaId() == 0) { CountDownLatch latch = cdl.get(); try { if (sleepTime.get() > 0) { LOG.info("Sleeping for " + sleepTime.get() + " ms"); Thread.sleep(sleepTime.get()); } else if (latch.getCount() > 0) { LOG.info("Waiting for the counterCountDownLatch"); latch.await(2, TimeUnit.MINUTES); // To help the tests to finish. if (latch.getCount() > 0) { throw new RuntimeException("Can't wait more"); } } } catch (InterruptedException e1) { LOG.error(e1); } } else { LOG.info("We're not the primary replicas."); } }
public void testPreferencesEvents() throws Exception { storage.toFolder(true); FileUtil.getConfigRoot().addRecursiveListener(new FileListener()); pref.addNodeChangeListener(new NodeListener()); String newPath = "a/b/c"; String[] paths = newPath.split("/"); FileObject fo = null; FileObject fo0 = null; for (int i = 0; i < paths.length; i++) { String path = paths[i]; fo = FileUtil.createFolder((fo == null) ? FileUtil.getConfigRoot() : fo, path); if (i == 0) { fo0 = fo; } nodeAddedEvent.await(); assertEquals("Missing node added event", 0, nodeAddedEvent.getCount()); nodeAddedEvent = new CountDownLatch(1); Preferences pref2 = pref.node(fo.getPath()); pref2.addNodeChangeListener(new NodeListener()); } FileObject fo1 = FileUtil.createData(fo, "a.properties"); nodeAddedEvent.await(); assertEquals("Missing node added event", 0, nodeAddedEvent.getCount()); nodeRemovedEvent = new CountDownLatch(paths.length + 1); fo0.delete(); nodeRemovedEvent.await(); assertEquals("Missing node removed event", 0, nodeRemovedEvent.getCount()); }
private void printMessage() { while (localByDravitController > 0) { if (byDravitController.getCount() < localByDravitController) { System.out.print(" By Dravit\n"); localByDravitController--; if (helloController.getCount() > 0) { helloController.countDown(); } } } }
public void awaitAndprintStatus() throws InterruptedException { out.print("progress: "); out.print(status(0)); backspace(2); while (latch.getCount() > 0) { latch.await(period, TimeUnit.SECONDS); String status = status(1 - (latch.getCount() * 1.0 / times)); out.print(status); backspace(status.length()); } out.println(status(1)); }
@Test public void testObjectHandler() throws DeploymentException, InterruptedException, IOException { final Server server = startServer(); CountDownLatch sentLatch = new CountDownLatch(MESSAGE_NO); CountDownLatch receivedLatch = new CountDownLatch(MESSAGE_NO); try { final ClientManager client = ClientManager.createClient(); client.connectToServer( new AsyncHandlerClient(sentLatch, receivedLatch), ClientEndpointConfig.Builder.create().build(), getURI(ObjectHandlerEndpoint.class.getAnnotation(ServerEndpoint.class).value())); sentLatch.await(5, TimeUnit.SECONDS); receivedLatch.await(5, TimeUnit.SECONDS); // Check the number of received messages Assert.assertEquals("Didn't send all the messages. ", 0, sentLatch.getCount()); Assert.assertEquals("Didn't receive all the messages. ", 0, receivedLatch.getCount()); final CountDownLatch serviceLatch = new CountDownLatch(1); client.connectToServer( new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { session.addMessageHandler( new MessageHandler.Whole<Integer>() { @Override public void onMessage(Integer message) { Assert.assertEquals( "Server callback wasn't called at all cases.", 0, message.intValue()); serviceLatch.countDown(); } }); try { session.getBasicRemote().sendText(ServiceEndpoint.OBJECT_HANDLER); } catch (IOException e) { e.printStackTrace(); } } }, ClientEndpointConfig.Builder.create().build(), getURI(ServiceEndpoint.class.getAnnotation(ServerEndpoint.class).value())); serviceLatch.await(5, TimeUnit.SECONDS); Assert.assertEquals("Didn't receive all the messages. ", 0, receivedLatch.getCount()); } finally { stopServer(server); } }
@Override public void run() { try { while (!finished && latch.getCount() > 0) { log.info( "There are " + latch.getCount() + " remaining schedules for the " + bucket + " data migration"); Thread.sleep(30000); } } catch (InterruptedException e) { } }
@Override public void run() { try { log.debug("run!"); this.root.setState(SubstepTestState.RUNNING); eventsConsumer.onEvent(new StateChangedEvent(this.root)); RootNode resultNode = getRootNodeFromBytes(jmxClient.runAsBytes()); // lets wait for any notifications try { countDownLatch.await(); } catch (InterruptedException e) { if (countDownLatch.getCount() > 0) { log.error("premature interupted ex waiting for complete notification"); } } if (resultNode.getResult().getResult() == com.technophobia.substeps.execution.ExecutionResult.PASSED) { this.root.setState(SubstepTestState.PASSED); } else if (resultNode.getResult().getResult() == com.technophobia.substeps.execution.ExecutionResult.FAILED) { this.root.setState(SubstepTestState.FAILED); } eventsConsumer.onEvent(new StateChangedEvent(this.root)); log.debug("done run, shutting down!"); } finally { jmxClient.shutdown(); log.debug("shut down done!"); } }
@Test public void testHttpWrappedContinuatuions() throws Exception { SpringBusFactory bf = new SpringBusFactory(); Bus bus = bf.createBus(CONFIG_FILE); BusFactory.setDefaultBus(bus); QName serviceName = new QName("http://cxf.apache.org/systest/jaxws", "HelloContinuationService"); URL wsdlURL = getClass().getResource("/org/apache/cxf/systest/jms/continuations/test.wsdl"); HelloContinuationService service = new HelloContinuationService(wsdlURL, serviceName); assertNotNull(service); final HelloContinuation helloPort = service.getHelloContinuationPort(); ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch helloDoneSignal = new CountDownLatch(5); executor.execute(new HelloWorker(helloPort, "Fred", "", startSignal, helloDoneSignal)); executor.execute(new HelloWorker(helloPort, "Barry", "Jameson", startSignal, helloDoneSignal)); executor.execute(new HelloWorker(helloPort, "Harry", "", startSignal, helloDoneSignal)); executor.execute(new HelloWorker(helloPort, "Rob", "Davidson", startSignal, helloDoneSignal)); executor.execute( new HelloWorker(helloPort, "James", "ServiceMix", startSignal, helloDoneSignal)); startSignal.countDown(); helloDoneSignal.await(60, TimeUnit.SECONDS); executor.shutdownNow(); assertEquals("Not all invocations have completed", 0, helloDoneSignal.getCount()); }
@Override public void run() { locator.setReconnectAttempts(0); final ClientSessionFactory sessionFactory; ClientSession session; try { sessionFactory = locator.createSessionFactory(tc); if (sessionFactory != null) { session = sessionFactory.createSession(); if (session != null) { if (nodeIsDown(total, count.incrementAndGet())) { while (latch.getCount() > 0) latch.countDown(); } session.close(); sessionFactory.close(); } } } catch (Exception e) { // no-op } finally { latch.countDown(); locator.close(); } }
@Test public void roundRobinLoadBalancing() throws Exception { int numberOfMessages = 11; ConcurrentTaskExecutor taskExecutor = new ConcurrentTaskExecutor( Executors.newSingleThreadScheduledExecutor(new CustomizableThreadFactory("test-"))); ExecutorChannel channel = new ExecutorChannel(taskExecutor, new RoundRobinLoadBalancingStrategy()); CountDownLatch latch = new CountDownLatch(numberOfMessages); TestHandler handler1 = new TestHandler(latch); TestHandler handler2 = new TestHandler(latch); TestHandler handler3 = new TestHandler(latch); channel.subscribe(handler1); channel.subscribe(handler2); channel.subscribe(handler3); for (int i = 0; i < numberOfMessages; i++) { channel.send(new GenericMessage<String>("test-" + i)); } latch.await(3000, TimeUnit.MILLISECONDS); assertEquals(0, latch.getCount()); assertNotNull(handler1.thread); assertFalse(Thread.currentThread().equals(handler1.thread)); assertTrue(handler1.thread.getName().startsWith("test-")); assertNotNull(handler2.thread); assertFalse(Thread.currentThread().equals(handler2.thread)); assertTrue(handler2.thread.getName().startsWith("test-")); assertNotNull(handler3.thread); assertFalse(Thread.currentThread().equals(handler3.thread)); assertTrue(handler3.thread.getName().startsWith("test-")); assertEquals(4, handler1.count.get()); assertEquals(4, handler2.count.get()); assertEquals(3, handler3.count.get()); }
public static void main(final String[] args) throws Exception { final JFrame frame = new DrawBitmaskToSurfaceTest(); frame.setBounds(10, 350, 200, 200); frame.setVisible(true); Thread.sleep(2000); System.err.println("Change frame bounds..."); latch = new CountDownLatch(1); frame.setBounds(10, 350, 90, 90); frame.repaint(); try { if (latch.getCount() > 0) { latch.await(); } } catch (InterruptedException e) { } frame.dispose(); if (theError != null) { throw new RuntimeException("Test failed.", theError); } System.err.println("Test passed"); }
protected void countDownCompletionLatch(int id) { final CountDownLatch countDownLatch = syncLocks.get(id); countDownLatch.countDown(); if (countDownLatch.getCount() == 0) { deregisterCompletionLatch(id); } }
// ------------------------------------------------------------------------- private void addMarketDataSubscriptions(final Set<ValueRequirement> requiredSubscriptions) { final OperationTimer timer = new OperationTimer( s_logger, "Adding {} market data subscriptions", requiredSubscriptions.size()); _pendingSubscriptions.addAll(requiredSubscriptions); _pendingSubscriptionLatch = new CountDownLatch(requiredSubscriptions.size()); getMarketDataProvider() .subscribe(getViewDefinition().getMarketDataUser(), requiredSubscriptions); _marketDataSubscriptions.addAll(requiredSubscriptions); try { if (!_pendingSubscriptionLatch.await(MARKET_DATA_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { long remainingCount = _pendingSubscriptionLatch.getCount(); s_logger.warn( "Timed out after {} ms waiting for market data subscriptions to be made. The market data " + "snapshot used in the computation cycle could be incomplete. Still waiting for {} out of {} market data " + "subscriptions", new Object[] { MARKET_DATA_TIMEOUT_MILLIS, remainingCount, _marketDataSubscriptions.size() }); } } catch (InterruptedException ex) { s_logger.info("Interrupted while waiting for subscription results."); } finally { _pendingSubscriptions.clear(); _pendingSubscriptionLatch = null; } timer.finished(); }
@Override public void handlePerspective( final Message<Event, Object> action, final PerspectiveLayout perspectiveLayout) { if (action.messageBodyEquals(MessageUtil.INIT)) { perspectiveLayout.registerRootComponent(createRoot()); GridPane.setVgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS); GridPane.setHgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS); // register left panel perspectiveLayout.registerTargetLayoutComponent("content0", this.content1); perspectiveLayout.registerTargetLayoutComponent("content1", this.content2); perspectiveLayout.registerTargetLayoutComponent("content2", this.content3); ApplicationLauncherPerspectiveMessaginTest.latch.countDown(); } else { if (counter.get() > 1) { counter.decrementAndGet(); context.send("id10", "message"); } else { System.out.println("Perspective id12: FINISH"); if (wait.getCount() > 0) wait.countDown(); if (PerspectiveMessagingTestP1.wait.getCount() > 0) context.send("id10", "message"); } } }
private void doReleaseLatches(Collection<CountDownLatch> barrierListCollection) { for (CountDownLatch latch : barrierListCollection) { while (latch.getCount() > 0) { latch.countDown(); } } }
@Test public void shouldTimeoutSleepingScript() throws Exception { final AtomicBoolean successCalled = new AtomicBoolean(false); final AtomicBoolean failureCalled = new AtomicBoolean(false); final CountDownLatch timeOutCount = new CountDownLatch(1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .scriptEvaluationTimeout(250) .afterFailure((b, e) -> failureCalled.set(true)) .afterSuccess((b) -> successCalled.set(true)) .afterTimeout((b) -> timeOutCount.countDown()) .create(); try { gremlinExecutor.eval("Thread.sleep(1000);10").get(); fail("This script should have timed out with an exception"); } catch (Exception ex) { assertEquals(TimeoutException.class, ex.getCause().getClass()); } assertTrue(timeOutCount.await(2000, TimeUnit.MILLISECONDS)); assertFalse(successCalled.get()); assertFalse(failureCalled.get()); assertEquals(0, timeOutCount.getCount()); gremlinExecutor.close(); }
@Test(enabled = false) public void testInvokeFunctionWithTrackMessageSizeDecoder_CombinedMessages() throws Exception { List<String> originalMessages = createMessages(5); List<String> modifiableMessages = new ArrayList<>(originalMessages); CountDownLatch latch = new CountDownLatch(modifiableMessages.size()); List<Decoder<?, ?>> decoders = withTrackMessageSizeDecoder(); List<FunctionWrapper> functions = withMessageFunction(modifiableMessages, latch); String firstMessage = originalMessages.get(0); String combinedMessages = ""; for (String message : originalMessages.subList(1, originalMessages.size())) { combinedMessages += withLengthPrefixed(message); } assertTrue( TransportsUtil.invokeFunction( decoders, functions, String.class, withLengthPrefixed(firstMessage), FUNCTION_NAME_MESSAGE, FunctionResolver.DEFAULT)); assertTrue( TransportsUtil.invokeFunction( decoders, functions, String.class, withLengthPrefixed(combinedMessages), FUNCTION_NAME_MESSAGE, FunctionResolver.DEFAULT)); assertTrue(latch.await(3, TimeUnit.SECONDS), "latch count was " + latch.getCount()); assertTrue(modifiableMessages.isEmpty()); }
public void run() { done.countDown(); remaining.incrementAndGet(); int n; while (!Thread.interrupted() && (n = remaining.get()) > 0 && done.getCount() > 0) { if (remaining.compareAndSet(n, n - 1)) { try { pool.execute(this); } catch (RuntimeException ex) { System.out.print("*"); while (done.getCount() > 0) done.countDown(); return; } } } }
private void runProxies( BookStore proxy, int numberOfClients, boolean threadSafe, boolean stateCanBeChanged) throws Exception { ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(numberOfClients); for (int i = 1; i <= numberOfClients; i++) { // here we do a double copy : from proxy to web client and back to proxy BookStore bs = !threadSafe ? JAXRSClientFactory.fromClient( WebClient.fromClient(WebClient.client(proxy)), BookStore.class) : proxy; String bookName = stateCanBeChanged ? Integer.toString(i) : "TheBook"; String bookHeader = stateCanBeChanged ? "value" + i : "CustomValue"; executor.execute( new RootProxyWorker( bs, bookName, bookHeader, startSignal, doneSignal, stateCanBeChanged)); } startSignal.countDown(); doneSignal.await(60, TimeUnit.SECONDS); executor.shutdownNow(); assertEquals("Not all invocations have completed", 0, doneSignal.getCount()); }
/** * Wait for a player to play. * * @param player the player to wait on * @param bridge the bridge for player * @param waiting a <code>CountDownLatch</code> used to wait for user input - must be non-null and * have and have <code>getCount()==1</code> * @return PlayData representing a play, or <code>null</code> if the play started and stopped on * the same <code>Territory</code> * @throws InterruptedException if the play was interrupted */ @Override public GridPlayData waitForPlay( final PlayerID player, final IPlayerBridge bridge, final CountDownLatch waiting) throws InterruptedException { // Make sure we have a valid CountDownLatch. if (waiting == null || waiting.getCount() != 1) throw new IllegalArgumentException("CountDownLatch must be non-null and have getCount()==1"); // The mouse listeners need access to the CountDownLatch, so store as a member variable. m_waiting = waiting; // Wait for a play or an attempt to leave the game m_waiting.await(); if (m_clickedAt == null) { // If m_clickedAt==null, // the play is invalid and must have been interrupted. // So, reset the member variable, and throw an exception. m_clickedAt = null; throw new InterruptedException("Interrupted while waiting for play."); } else { // We have a valid play! // Reset the member variables, and return the play. final Territory play = m_clickedAt; m_clickedAt = null; return new GridPlayData(play, null, player); } }
@Override public void onMessage(final ClientMessage message) { try { if (!started) { failed = true; } messageReceived++; log.info("got message " + messageReceived); latch.countDown(); if (latch.getCount() == 0) { message.acknowledge(); started = false; consumer.setMessageHandler(null); } } catch (Exception e) { } }
@Test public void testHttpServer() throws IOException, ExecutionException, InterruptedException { final CountDownLatch lock = new CountDownLatch(CONCURRENT_REQUESTS); for (int i = 0; i < CONCURRENT_REQUESTS; i++) { TrackingDataTO trackingDataTO = bootstrapTrackingData(); String requestAsJson = gson.toJson(trackingDataTO); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); asyncHttpClient .preparePost("http://localhost:8080/" + trackingDataTO.getType().getLabel()) .setBody(requestAsJson) .execute( new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { ResultTO resultTo = gson.fromJson(response.getResponseBody(), ResultTO.class); if (resultTo.getCode().equals(ResultCode.SUCCESS)) { lock.countDown(); } return response; } @Override public void onThrowable(Throwable t) { log.error(t.toString()); } }); } lock.await(TIMEOUT, TimeUnit.MILLISECONDS); assertEquals(0, lock.getCount()); }
@Test public void testPublisherConfirmReceived() throws Exception { final CountDownLatch latch = new CountDownLatch(10000); final AtomicInteger acks = new AtomicInteger(); templateWithConfirmsEnabled.setConfirmCallback( new ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { acks.incrementAndGet(); latch.countDown(); } }); ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 100; i++) { exec.submit( new Runnable() { @Override public void run() { try { for (int i = 0; i < 100; i++) { templateWithConfirmsEnabled.convertAndSend( ROUTE, (Object) "message", new CorrelationData("abc")); } } catch (Throwable t) { t.printStackTrace(); } } }); } exec.shutdown(); assertTrue(exec.awaitTermination(300, TimeUnit.SECONDS)); assertTrue("" + latch.getCount(), latch.await(60, TimeUnit.SECONDS)); assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1)); this.templateWithConfirmsEnabled.execute( new ChannelCallback<Void>() { @Override public Void doInRabbit(Channel channel) throws Exception { Map<?, ?> listenerMap = TestUtils.getPropertyValue( ((ChannelProxy) channel).getTargetChannel(), "listenerForSeq", Map.class); int n = 0; while (n++ < 100 && listenerMap.size() > 0) { Thread.sleep(100); } assertEquals(0, listenerMap.size()); return null; } }); Log logger = spy(TestUtils.getPropertyValue(connectionFactoryWithConfirmsEnabled, "logger", Log.class)); new DirectFieldAccessor(connectionFactoryWithConfirmsEnabled) .setPropertyValue("logger", logger); cleanUp(); verify(logger, never()).error(any()); }
/** {@inheritDoc} */ @Override public void onUpdate(int cnt) { assert cnt >= 0; this.cnt = cnt; while (internalLatch != null && internalLatch.getCount() > cnt) internalLatch.countDown(); }
public StatementIteratorConsumer( BoundedCQLStatementIterator statementIterator, CQLExecutor cqlExecutor, long timeout) { this.statementIterator = statementIterator; this.cqlExecutor = cqlExecutor; this.timeout = timeout; this.shutdownLatch = new CountDownLatch((new Long(statementIterator.size())).intValue()); logger.trace("Created consumer with countdown {}", shutdownLatch.getCount()); }
public void process(WatchedEvent event) { LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath()); if (event.getState() == KeeperState.SyncConnected && startSignal != null && startSignal.getCount() > 0) { startSignal.countDown(); } }
@Test public void testBeamModeMonitor() throws Exception { final BeamModeMonitor mm = new BeamModeMonitor(this); mm.start(); done.await(5, TimeUnit.SECONDS); mm.stop(); assertEquals(done.getCount(), 0); }
public void testPreferencesEvents2() throws Exception { pref.addNodeChangeListener(new NodeListener()); pref.addPreferenceChangeListener(new PrefListener()); Preferences child = pref.node("a"); nodeAddedEvent.await(); assertEquals("Missing node added event", 0, nodeAddedEvent.getCount()); pref.put("key", "value"); prefChangedEvent.await(); assertEquals("Missing preference change event", 0, prefChangedEvent.getCount()); pref.remove("key"); prefRemovedEvent.await(); assertEquals("Missing preference removed event", 0, prefRemovedEvent.getCount()); child.removeNode(); nodeRemovedEvent.await(); assertEquals("Missing node removed event", 0, nodeRemovedEvent.getCount()); }