List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:org.mule.service.http.impl.functional.server.HttpServerClientTimeoutTestCase.java
@Before public void setUp() throws Exception { requestLatch = new CountDownLatch(1); responseLatch = new CountDownLatch(1); server = service.getServerFactory().create(new HttpServerConfiguration.Builder().setHost("localhost") .setPort(port.getNumber()).setName("client-timeout-test").build()); server.start();//w w w . j ava2s. co m server.addRequestHandler(singletonList(GET.name()), "/test", (requestContext, responseCallback) -> { try { requestLatch.await(); } catch (InterruptedException e) { // Nothing to do } responseCallback.responseReady( HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode()) .entity(new ByteArrayHttpEntity("Success!".getBytes())) .addHeader(CONTENT_TYPE, TEXT.toRfcString()).build(), new IgnoreResponseStatusCallback() { @Override public void responseSendSuccessfully() { responseLatch.countDown(); } }); }); }
From source file:com.netflix.curator.framework.imps.TestFailedDeleteManager.java
@Test public void testLostSession() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); try {//from ww w . ja v a 2 s .c om client.start(); client.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { client.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch (KeeperException.ConnectionLossException e) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test-me")); } finally { IOUtils.closeQuietly(client); } }
From source file:ufo.remote.calls.benchmark.client.caller.vertx.VertxClusterTester.java
@PostConstruct public void init() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final VertxOptions options = new VertxOptions(); final Config conf = new Config(); Vertx.clusteredVertx(options.setClusterHost("localhost").setClusterPort(0).setClustered(true) .setClusterManager(new HazelcastClusterManager(conf)), ar -> { if (ar.failed()) { logger.error("Error starting Vertx cluster", ar.cause()); }// w w w .j a v a 2 s . com logger.info("Vertx cluster node started [{}]"); vertx = ar.result(); logger.info("Initialising vertx verticles..."); latch.countDown(); }); latch.await(); }
From source file:com.netflix.curator.framework.recipes.shared.TestSharedCount.java
@Test public void testMultiClients() throws Exception { final int CLIENT_QTY = 5; List<Future<List<Integer>>> futures = Lists.newArrayList(); final List<CuratorFramework> clients = new CopyOnWriteArrayList<CuratorFramework>(); try {//from w w w . j a v a 2 s .c om final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY); final Semaphore semaphore = new Semaphore(0); ExecutorService service = Executors .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build()); for (int i = 0; i < CLIENT_QTY; ++i) { Future<List<Integer>> future = service.submit(new Callable<List<Integer>>() { @Override public List<Integer> call() throws Exception { final List<Integer> countList = Lists.newArrayList(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients.add(client); client.start(); SharedCount count = new SharedCount(client, "/count", 10); final CountDownLatch latch = new CountDownLatch(1); count.addListener(new SharedCountListener() { @Override public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { if (newCount < 0) { latch.countDown(); } else { countList.add(newCount); } semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }); count.start(); startLatch.countDown(); latch.await(); return countList; } }); futures.add(future); } CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients.add(client); client.start(); Assert.assertTrue(startLatch.await(10, TimeUnit.SECONDS)); SharedCount count = new SharedCount(client, "/count", 10); count.start(); List<Integer> countList = Lists.newArrayList(); Random random = new Random(); for (int i = 0; i < 100; ++i) { Thread.sleep(random.nextInt(10)); int next = random.nextInt(100); countList.add(next); count.setCount(next); Assert.assertTrue(semaphore.tryAcquire(CLIENT_QTY, 10, TimeUnit.SECONDS)); } count.setCount(-1); for (Future<List<Integer>> future : futures) { List<Integer> thisCountList = future.get(); Assert.assertEquals(thisCountList, countList); } } finally { for (CuratorFramework client : clients) { IOUtils.closeQuietly(client); } } }
From source file:io.undertow.server.handlers.accesslog.AccessLogTestCase.java
@Test public void testRemoteAddress() throws IOException, InterruptedException { latch = new CountDownLatch(1); DefaultServer.setRootHandler(new AccessLogHandler(HELLO_HANDLER, RECEIVER, "Remote address %a Code %s test-header %{i,test-header}", AccessLogFileTestCase.class.getClassLoader())); TestHttpClient client = new TestHttpClient(); try {// w w w . j a v a 2 s. c o m HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); get.addHeader("test-header", "test-value"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Hello", HttpClientUtils.readResponse(result)); latch.await(10, TimeUnit.SECONDS); Assert.assertEquals( "Remote address " + DefaultServer.getDefaultServerAddress().getAddress().getHostAddress() + " Code 200 test-header test-value", message); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.yozio.android.YozioHelperTest.java
public void testInitializeExperimentsAsync() throws Throwable { JSONObject configs = null;/*from w w w . j a va 2s . c o m*/ try { configs = new JSONObject().put("key", "123"); fakeApiService.setExperimentConfigs(configs); } catch (JSONException e) { fail(); } final CountDownLatch signal = new CountDownLatch(1); runTestOnUiThread(new Runnable() { public void run() { helper.initializeExperimentsAsync(new InitializeExperimentsCallback() { public void onComplete() { assertEquals(123, helper.intForKey("key", 111)); signal.countDown(); } }); } }); signal.await(10, TimeUnit.SECONDS); }
From source file:org.mule.module.http.functional.listener.HttpListenerNotificationsTestCase.java
@Test public void receiveNotification() throws Exception { String listenerUrl = String.format("http://localhost:%s/%s", listenPort.getNumber(), path.getValue()); CountDownLatch latch = new CountDownLatch(2); TestConnectorMessageNotificationListener listener = new TestConnectorMessageNotificationListener(latch, listenerUrl);//from w w w. j a va 2s. co m muleContext.getNotificationManager().addListener(listener); Request.Post(listenerUrl).execute(); latch.await(1000, TimeUnit.MILLISECONDS); assertThat(listener.getNotificationActionNames(), contains(getActionName(MESSAGE_RECEIVED), getActionName(MESSAGE_RESPONSE))); }
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.j a va 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.github.oscerd.component.cassandra.embedded.CassandraBaseCounterTest.java
@Override public void doPostSetup() { String id = RandomStringUtils.random(12, "0123456789abcdefghijklmnopqrstuvwxyz"); fs = new Farsandra(); fs.withVersion("2.0.3"); fs.withCleanInstanceOnStart(true);//from ww w .ja v a 2s . c o m fs.withInstanceName("target" + File.separator + id); fs.withCreateConfigurationFiles(true); fs.withHost("localhost"); fs.withSeeds(Arrays.asList("localhost")); final CountDownLatch started = new CountDownLatch(1); fs.getManager().addOutLineHandler(new LineHandler() { @Override public void handleLine(String line) { if (line.contains("Listening for thrift clients...")) { started.countDown(); } } }); fs.getManager().addProcessHandler(new ProcessHandler() { @Override public void handleTermination(int exitValue) { started.countDown(); } }); fs.start(); try { started.await(); Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Session session = cluster.connect(); session.execute("CREATE KEYSPACE IF NOT EXISTS simplex WITH replication " + "= {'class':'SimpleStrategy', 'replication_factor':3};"); session.execute( "CREATE TABLE IF NOT EXISTS simplex.counter (" + "like counter, " + "id int PRIMARY KEY" + ");"); session.close(); session = cluster.connect("simplex"); Where update = QueryBuilder.update("counter").with(QueryBuilder.incr("like", 1)) .where(QueryBuilder.eq("id", 1)); session.execute(update); session.close(); cluster.close(); try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.usergrid.benchmark.commands.queue.QueueReader.java
@Override protected void doWork(CommandLine line, Queue<TestEvent> queue, String hostName, int workers, int count) throws Exception { CountDownLatch latch = new CountDownLatch(count * workers); queue.observe(new EventListener(latch, readsTimer, readLogger, queue)); latch.await();//from w ww. j a v a2s . c o m writeTimerData(readsTimer); }