List of usage examples for java.util.concurrent CountDownLatch await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
From source file:ch.windmobile.server.socialmodel.mogodb.HeavyLoadTest.java
public void testFullChatCycle() throws Exception { ServiceLocator locator = new MongoDBServiceLocator().connect(null); try {/*from ww w.j a v a 2s. co m*/ final int CNT = 50000; final Executor executor = Executors.newFixedThreadPool(10); final ChatService chatService = locator.getService(ChatService.class); final AtomicInteger counter = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(CNT); for (int i = 0; i < CNT; i++) { executor.execute(new Runnable() { @Override public void run() { chatService.postMessage("TestRoom", "aUser", "Hello, this is my message " + counter.incrementAndGet(), ""); latch.countDown(); } }); } System.out.println("Chat sent, waiting for the end..."); latch.await(2, TimeUnit.MINUTES); Messages ret = chatService.findMessages("TEST", 5); System.out.println("result : " + ret); } finally { locator.disconnect(); } }
From source file:org.smartfrog.services.anubis.SmokeTest.java
public void testInProcess() throws Exception { TestNodeCfg.nextMagic();/*from ww w .j a va 2 s. c o m*/ String stateName = "Whip It"; int maxSleep = 500; int messageCount = 10; ArrayList<Node> nodes = new ArrayList<Node>(); CountDownLatch launchLatch = new CountDownLatch(configurations.length); CountDownLatch startLatch = new CountDownLatch(configurations.length); CountDownLatch endLatch = new CountDownLatch(configurations.length); for (Class<?> config : configurations) { nodes.add(getNode(config, stateName, messageCount, maxSleep, launchLatch, startLatch, endLatch, configurations.length)); } boolean stabilized = launchLatch.await(120, TimeUnit.SECONDS); assertTrue("Partition did not stabilize", stabilized); System.out.println("Partition stabilized"); for (Node node : nodes) { node.start(); } boolean started = startLatch.await(60, TimeUnit.SECONDS); assertTrue("Not all nodes started", started); System.out.println("Partition started"); boolean ended = endLatch.await(60, TimeUnit.SECONDS); assertTrue("Not all messages were received: " + findMissing(nodes), ended); for (Node node : nodes) { node.shutDown(); } for (Node sender : nodes) { List<SendHistory> sent = sender.getSendHistory(); assertEquals(messageCount, sent.size()); for (Node receiver : nodes) { List<ValueHistory> received = receiver.getValueHistory(sender.getIdentity()); assertNotNull("Received no history from " + sender.getIdentity(), received); int lastCounter = -1; boolean first = true; List<ValueHistory> filtered = new ArrayList<ValueHistory>(); for (ValueHistory msg : received) { if (msg.value == null) { continue; } filtered.add(msg); assertEquals(Action.NEW, msg.action); if (first) { first = false; lastCounter = (Integer) msg.value; } else { int counter = (Integer) msg.value; assertEquals(String.format("invalid msg received by %s : %s", receiver.getIdentity(), msg), lastCounter + 1, counter); lastCounter = counter; } } for (int i = 0; i < sent.size(); i++) { assertEquals(sent.get(i).value, filtered.get(i).value); } } } }
From source file:com.doctor.esper.reference_5_2_0.Chapter21Performance.java
/** * We recommend using multiple threads to send events into Esper. We provide a test class below. Our test class does not use a blocking queue and thread pool so as to avoid a point of contention. * /*from www . ja va 2 s . com*/ * ???Esper?? * * * We recommend using Java threads as test_testing_performance_with_multiple_threads() , or a blocking queue and thread pool with sendEvent() or alternatively we recommend configuring inbound threading if your application does not already employ threading. Esper provides the configuration * option to use engine-level queues and threadpools for inbound, outbound and internal executions. See Section 15.7.1, Advanced Threading? for more information. * * ?http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#config-engine-threading * * @throws InterruptedException */ @Test public void test_testing_performance_with_multiple_threads() throws InterruptedException { int numEvents = 1000000; int numThreads = 3; Thread[] threads = new Thread[numThreads]; CountDownLatch countDownLatch = new CountDownLatch(numThreads); int eventPerThreads = numEvents / numThreads; for (int i = 0; i < numThreads; i++) { threads[i] = new Thread(new MyRunnable(countDownLatch, eventPerThreads, esperTemplateBean)); } Stopwatch stopwatch = Stopwatch.createStarted(); for (int i = 0; i < numThreads; i++) { threads[i].start(); } countDownLatch.await(10, TimeUnit.MINUTES); if (countDownLatch.getCount() > 0) { throw new RuntimeException("Failed to complete in 10 minute"); } System.out.println("Took " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "milliseconds "); }
From source file:io.fabric8.agent.DownloadManagerTest.java
@Test public void testDownloadUsingNonAuthenticatedProxy() throws Exception { Server server = new Server(0); server.setHandler(new AbstractHandler() { @Override/*from w w w . ja v a 2s .c o m*/ public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getOutputStream().write(new byte[] { 0x42 }); response.getOutputStream().close(); } }); server.start(); Properties custom = new Properties(); custom.setProperty("org.ops4j.pax.url.mvn.proxySupport", "true"); String settings = createMavenSettingsWithProxy(server.getConnectors()[0].getLocalPort()); DownloadManager dm = createDownloadManager("http://relevant.not/maven2@id=central", settings, custom); try { final CountDownLatch latch = new CountDownLatch(1); DownloadFuture df = dm.download("mvn:x.y/z/1.0"); df.addListener(new FutureListener<DownloadFuture>() { @Override public void operationComplete(DownloadFuture future) { latch.countDown(); } }); latch.await(30, TimeUnit.SECONDS); assertNotNull(df.getUrl()); assertNotNull(df.getFile()); assertEquals("z-1.0.jar", df.getFile().getName()); LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile()); } finally { server.stop(); } }
From source file:com.asakusafw.runtime.util.cache.HadoopFileCacheRepositoryTest.java
/** * Conflict cache creation./* w w w. j a va2 s .co m*/ * @throws Exception if failed */ @Test public void conflict() throws Exception { File source = folder.newFile(); byte[] bytes = new byte[1024 * 1024]; try (OutputStream output = new FileOutputStream(source)) { for (int i = 0, n = 50; i < n; i++) { output.write(bytes); } } Path path = path(source); File cacheRepo = folder.newFolder(); Configuration configuration = new ConfigurationProvider().newInstance(); LockProvider<Path> locks = new LocalFileLockProvider<>(folder.newFolder()); RetryStrategy retrier = new ConstantRetryStrategy(30, 100, 200); FileCacheRepository cache = new HadoopFileCacheRepository(configuration, path(cacheRepo), locks, retrier); List<Future<Path>> futures = new ArrayList<>(); int count = 10; CountDownLatch latch = new CountDownLatch(count); ExecutorService executor = Executors.newFixedThreadPool(count); try { for (int i = 0; i < count; i++) { String label = String.format("thread-%d", i); futures.add(executor.submit(() -> { LOG.info("Wait: resolve @" + label); latch.countDown(); if (latch.await(5, TimeUnit.SECONDS) == false) { throw new TimeoutException(); } LOG.info("Start: resolve @" + label); Path result = cache.resolve(path); LOG.info("Finish: resolve @" + label); return result; })); } executor.shutdown(); if (executor.awaitTermination(30, TimeUnit.SECONDS) == false) { throw new TimeoutException(); } } finally { executor.shutdownNow(); } for (Future<Path> future : futures) { future.get(); } }
From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java
public static <H extends ServiceHost> void deleteAllDocuments(H host, String referrer, long timeout, TimeUnit timeUnit) throws Throwable { QueryTask.Query selfLinkClause = new QueryTask.Query() .setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK).setTermMatchValue("*") .setTermMatchType(QueryTask.QueryTerm.MatchType.WILDCARD); QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification(); querySpecification.query.addBooleanClause(selfLinkClause); QueryTask queryTask = QueryTask.create(querySpecification).setDirect(true); NodeGroupBroadcastResponse queryResponse = ServiceHostUtils.sendBroadcastQueryAndWait(host, referrer, queryTask);//from w w w . j av a 2s .c o m Set<String> documentLinks = QueryTaskUtils.getBroadcastQueryResults(queryResponse); if (documentLinks == null || documentLinks.size() <= 0) { return; } CountDownLatch latch = new CountDownLatch(1); OperationJoin.JoinedCompletionHandler handler = new OperationJoin.JoinedCompletionHandler() { @Override public void handle(Map<Long, Operation> ops, Map<Long, Throwable> failures) { if (failures != null && !failures.isEmpty()) { for (Throwable e : failures.values()) { logger.error("deleteAllDocuments failed", e); } } latch.countDown(); } }; Collection<Operation> deletes = new LinkedList<>(); for (String documentLink : documentLinks) { Operation deleteOperation = Operation.createDelete(UriUtils.buildUri(host, documentLink)).setBody("{}") .setReferer(UriUtils.buildUri(host, referrer)); deletes.add(deleteOperation); } OperationJoin join = OperationJoin.create(deletes); join.setCompletion(handler); join.sendWith(host); if (!latch.await(timeout, timeUnit)) { throw new TimeoutException(String .format("Deletion of all documents timed out. Timeout:{%s}, TimeUnit:{%s}", timeout, timeUnit)); } }
From source file:de.jackwhite20.japs.shared.nio.NioSocketClient.java
public boolean connect(String host, int port) { ChannelFuture channelFuture = new Bootstrap().group(PipelineUtils.newEventLoopGroup(1)) .channel(PipelineUtils.getChannel()).handler(new ClientChannelInitializer(this)) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT).connect(host, port); channelFuture.awaitUninterruptibly(); channel = channelFuture.channel();//from w w w. j a v a 2 s .c o m CountDownLatch countDownLatch = new CountDownLatch(1); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { connected = channelFuture.isSuccess(); countDownLatch.countDown(); } }); try { countDownLatch.await(2, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } return connected; }
From source file:io.fabric8.agent.DownloadManagerTest.java
@Test public void testDownloadUsingAuthenticatedProxy() throws Exception { Server server = new Server(0); server.setHandler(new AbstractHandler() { @Override/*w w w .j av a2s.c om*/ public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String proxyAuth = request.getHeader("Proxy-Authorization"); if (proxyAuth == null || proxyAuth.trim().equals("")) { response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); response.addHeader("Proxy-Authenticate", "Basic realm=\"Proxy Server\""); baseRequest.setHandled(true); } else { response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getOutputStream().write(new byte[] { 0x42 }); response.getOutputStream().close(); } } }); server.start(); Properties custom = new Properties(); custom.setProperty("org.ops4j.pax.url.mvn.proxySupport", "true"); String settings = createMavenSettingsWithProxy(server.getConnectors()[0].getLocalPort()); DownloadManager dm = createDownloadManager("http://relevant.not/maven2@id=central", settings, custom); try { final CountDownLatch latch = new CountDownLatch(1); DownloadFuture df = dm.download("mvn:x.y/z/1.0"); df.addListener(new FutureListener<DownloadFuture>() { @Override public void operationComplete(DownloadFuture future) { latch.countDown(); } }); latch.await(30, TimeUnit.SECONDS); assertNotNull(df.getUrl()); assertNotNull(df.getFile()); assertEquals("z-1.0.jar", df.getFile().getName()); LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile()); } finally { server.stop(); } }
From source file:com.alibaba.wasp.master.TestMaster.java
@Test public void testMasterOpsWhileSplitting() throws Exception { MiniWaspCluster cluster = TEST_UTIL.getWaspCluster(); FMaster m = cluster.getMaster();//from w ww. j ava 2 s . c o m FTable ft = TEST_UTIL.createTable(TABLENAME); assertTrue(m.assignmentManager.getZKTable().isEnabledTable(Bytes.toString(TABLENAME))); TEST_UTIL.loadTable(ft); List<Pair<EntityGroupInfo, ServerName>> tableEntityGroups = FMetaReader .getTableEntityGroupsAndLocations(TEST_UTIL.getConfiguration(), TABLENAME); LOG.info("EntityGroups after load: " + Joiner.on(',').join(tableEntityGroups)); assertEquals(1, tableEntityGroups.size()); assertArrayEquals(FConstants.EMPTY_START_ROW, tableEntityGroups.get(0).getFirst().getStartKey()); assertArrayEquals(FConstants.EMPTY_END_ROW, tableEntityGroups.get(0).getFirst().getEndKey()); // Now trigger a split and stop when the split is in progress CountDownLatch split = new CountDownLatch(1); CountDownLatch proceed = new CountDownLatch(1); EntityGroupSplitListener list = new EntityGroupSplitListener(split, proceed); cluster.getMaster().executorService.registerListener(EventType.FSERVER_ZK_ENTITYGROUP_SPLIT, list); LOG.info("Splitting table"); TEST_UTIL.getWaspAdmin().split(TABLENAME, Bytes.toBytes("1234")); LOG.info("Waiting for split result to be about to open"); split.await(60, TimeUnit.SECONDS); try { LOG.info("Making sure we can call getTableEntityGroups while opening"); tableEntityGroups = FMetaReader.getTableEntityGroupsAndLocations(TEST_UTIL.getConfiguration(), TABLENAME, false); LOG.info("EntityGroups: " + Joiner.on(',').join(tableEntityGroups)); // We have three entitygroups because one is split-in-progress assertEquals(3, tableEntityGroups.size()); LOG.info("Making sure we can call getTableEntityGroupClosest while opening"); Pair<EntityGroupInfo, ServerName> pair = m.getTableEntityGroupForRow(TABLENAME, Bytes.toBytes("cde")); LOG.info("Result is: " + pair); Pair<EntityGroupInfo, ServerName> tableEntityGroupFromName = FMetaReader .getEntityGroup(TEST_UTIL.getConfiguration(), pair.getFirst().getEntityGroupName()); assertEquals(tableEntityGroupFromName.getFirst(), pair.getFirst()); } finally { proceed.countDown(); } }
From source file:com.onyxscheduler.domain.SchedulerIT.java
@Test public void shouldStopFiringCronJobAfterDeleted() throws Scheduler.DuplicateJobKeyException, InterruptedException { CountDownLatch latch = new CountDownLatch(2); latchProvider.setLatch(latch);//from w ww. j a v a2 s .c om scheduler.scheduleJob(buildEvery2SecondsCronJob()); scheduler.deleteJob(new JobKey(JOB_GROUP, JOB_NAME)); assertThat(latch.await(FIRE_THRESHOLD_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS), is(false)); }