List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:com.apachecon.camel.filesplit.FileSplitTest.java
@Test public void testFileSplitParallelProc() throws Exception { PropertiesComponent props = context.getRegistry().lookup("properties", PropertiesComponent.class); int count = Integer.parseInt(props.parseUri("{{demo.message.count}}")); CountDownLatch trigger = new CountDownLatch(count); SplitCounterProcessor splitCounter = context.getRegistry().lookup("splitCounter", SplitCounterProcessor.class); splitCounter.setCounter(trigger);// w w w .jav a 2s. c o m // file poller starts automatically when the route starts // since we created the 'fetch' route with autoStartup=false // polling won't start until we start the route log.info("Expecting to process {} messages", count); context.startRoute("fetch"); // set a timeout larger than the expected processing time int timeout = 10 * 1000; boolean success = trigger.await(timeout, TimeUnit.MILLISECONDS); long delta = success ? System.currentTimeMillis() - splitCounter.getTimeStarted() : timeout; String outcome = success ? "finished in" : "timed out after"; log.info("Processing {} {} millis", outcome, delta); assertTrue(success); }
From source file:CountUpDownLatch.java
public CountUpDownLatch() { latch = new CountDownLatch(1); this.count = count; }
From source file:com.alibaba.simpleimage.ColorQuantPerfTest.java
public void start() throws InterruptedException { CountDownLatch latch = new CountDownLatch(times); File rootDir = new File(new File(appDir), "/src/test/resources/conf.test/simpleimage"); for (int s = 0; s < threadsNum; s++) { Thread t = new Thread(new Worker(latch, rootDir, algName)); t.start();//from ww w .j av a 2 s . c o m } latch.await(); }
From source file:com.example.grpc.springboot.Cmd.java
@Override public void run(String... args) throws Exception { Channel channel = channelFactory.createChannel("EchoService"); CountDownLatch latch = new CountDownLatch(1); EchoServiceStub stub = EchoServiceGrpc.newStub(channel); for (int i = 0; i < 10; ++i) { stub.echo(Echo.newBuilder().setMessage("Hello" + i).build(), new StreamObserver<Echo>() { @Override//from w w w . j a v a2 s . c om public void onNext(Echo value) { System.out.println(value.getMessage()); } @Override public void onError(Throwable t) { latch.countDown(); } @Override public void onCompleted() { System.out.println("Finished"); latch.countDown(); } }); } latch.await(); }
From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorParticipants.java
@Test public void testId() throws Exception { LeaderSelector selector = null;/*from w ww .j a va2 s.c om*/ CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final CountDownLatch latch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { latch.countDown(); Thread.currentThread().join(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; selector = new LeaderSelector(client, "/ls", listener); selector.setId("A is A"); selector.start(); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Participant leader = selector.getLeader(); Assert.assertTrue(leader.isLeader()); Assert.assertEquals(leader.getId(), "A is A"); Collection<Participant> participants = selector.getParticipants(); Assert.assertEquals(participants.size(), 1); Assert.assertEquals(participants.iterator().next().getId(), "A is A"); Assert.assertEquals(participants.iterator().next().getId(), selector.getId()); } finally { IOUtils.closeQuietly(selector); IOUtils.closeQuietly(client); } }
From source file:com.test.database.jedis.TestJedisEvalLua.java
public static void generateTestData() throws InterruptedException { Jedis jedis = new Jedis(host, port); jedis.flushAll();//from ww w . ja v a2 s. c om jedis.close(); final CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; ++i) { final int temp = i; Thread thread = new Thread() { public void run() { Jedis jedis = new Jedis(host, port); int per = honBaoCount / threadCount; JSONObject object = new JSONObject(); for (int j = temp * per; j < (temp + 1) * per; j++) { object.put("id", j); object.put("money", j); jedis.lpush(hongBaoList, object.toString()); } latch.countDown(); jedis.close(); } }; thread.start(); } latch.await(); }
From source file:com.netflix.curator.framework.imps.TestMultiClient.java
@Test public void testNotify() throws Exception { CuratorFramework client1 = null;//from w w w .ja v a 2 s.c o m CuratorFramework client2 = null; try { client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client1.start(); client2.start(); final CountDownLatch latch = new CountDownLatch(1); client1.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if (event.getType() == CuratorEventType.WATCHED) { if (event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged) { if (event.getPath().equals("/test")) { latch.countDown(); } } } } }); client1.create().forPath("/test", new byte[] { 1, 2, 3 }); client1.checkExists().watched().forPath("/test"); client2.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if (event.getType() == CuratorEventType.SYNC) { client.setData().forPath("/test", new byte[] { 10, 20 }); } } }); client2.sync("/test", null); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { IOUtils.closeQuietly(client1); IOUtils.closeQuietly(client2); } }
From source file:co.cask.tigon.sql.internal.HealthAndMetricsTest.java
@BeforeClass public static void setup() throws Exception { failureLatch = new CountDownLatch(1); pingLatch = new CountDownLatch(PING_COUNT); HubDataStore hubDataStore = new HubDataStore.Builder().setInstanceName("test").build(); inspector = new HealthInspector(new ProcessMonitor() { @Override/*from w w w . j a v a 2 s. c o m*/ public void notifyFailure(Set<String> errorProcessNames) { LOG.info("Heartbeat detection failure notified"); for (String error : errorProcessNames) { LOG.error("No Heartbeat received from " + error); } failureLatch.countDown(); } @Override public void announceReady() { //no-op } }); metrics = new SharedMetrics(); MetricsRecorder metricsRecorder = new MetricsRecorder(metrics); discoveryServer = new DiscoveryServer(hubDataStore, inspector, metricsRecorder, new ProcessMonitor() { @Override public void notifyFailure(Set<String> errorProcessNames) { //no-op } @Override public void announceReady() { //no-op } }); discoveryServer.startAndWait(); }
From source file:com.yimidida.shards.strategy.access.impl.ParallelShardAccessStrategy.java
@Override public <T> T apply(List<Shard> shards, ShardOperation<T> operation, ExitStrategy<T> exitStrategy, ExitOperationsCollector exitOperationsCollector) { List<StartAwareFutureTask> tasks = Lists.newArrayListWithCapacity(shards.size()); int taskId = 0; /**/*from w w w. j a va2 s. c o m*/ * Used to prevent threads for processing until all tasks have been * submitted, otherwise we risk tasks that want to cancel other tasks * that have not yet been scheduled. */ CountDownLatch startSignal = new CountDownLatch(1); /** * Used to signal this thread that all processing is complete */ CountDownLatch doneSignal = new CountDownLatch(shards.size()); for (final Shard shard : shards) { // create a task for each shard for (final ShardId shardId : shard.getShardIds()) { ParallelShardOperationCallable<T> callable = new ParallelShardOperationCallable<T>(startSignal, doneSignal, exitStrategy, operation, shard, shardId, tasks); // wrap the task in a StartAwareFutureTask so that the task can be cancelled StartAwareFutureTask ft = new StartAwareFutureTask(callable, taskId++); tasks.add(ft); // hand the task off to the executor for execution executor.execute(ft); } } // the tasks List is populated, release the threads! startSignal.countDown(); try { log.debug("Waiting for threads to complete processing before proceeding."); //TODO(maxr) let users customize timeout behavior /* if(!doneSignal.await(10, TimeUnit.SECONDS)) { final String msg = "Parallel operations timed out."; log.error(msg); throw new HibernateException(msg); } */ // now we wait until all threads finish doneSignal.await(); } catch (InterruptedException e) { // not sure why this would happen or what we should do if it does log.error("Received unexpected exception while waiting for done signal.", e); } log.debug("Compiling results."); return exitStrategy.compileResults(exitOperationsCollector); }
From source file:com.qualys.jserf.SerfClientIT.java
@Test(timeout = 10000) public void testHandShake() throws Exception { while (!client.isConnected()) { Thread.sleep(500);//from ww w . j av a 2 s. co m } final boolean[] callbackInvoked = { false }; final CountDownLatch latch = new CountDownLatch(1); SerfResponseCallBack<EmptyResponseBody> callBack = new SerfResponseCallBack<EmptyResponseBody>() { @Override public void call(SerfResponse<EmptyResponseBody> response) { log.debug("Received call back with sequence {}", response.getHeader().getSeq()); callbackInvoked[0] = true; assertNotNull(response.getHeader()); assertEquals(StringUtils.EMPTY, response.getHeader().getError()); assertNotNull(response.getBody()); assertEquals(EmptyResponseBody.class, response.getBody().getClass()); //don't count down unless all the asserts pass latch.countDown(); } }; SerfRequest request = SerfRequests.handshake(callBack); client.makeRpc(request); latch.await(); assertTrue(callbackInvoked[0]); }