List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java
@Test public void testCustomExecutor() throws Exception { final int ITERATIONS = 1000; Timing timing = new Timing(); DistributedQueue<String> queue = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start();// w w w .ja v a 2 s .c o m try { final CountDownLatch latch = new CountDownLatch(ITERATIONS); QueueConsumer<String> consumer = new QueueConsumer<String>() { @Override public void consumeMessage(String message) throws Exception { latch.countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; QueueSerializer<String> serializer = new QueueSerializer<String>() { @Override public byte[] serialize(String item) { return item.getBytes(); } @Override public String deserialize(byte[] bytes) { return new String(bytes); } }; Executor executor = Executors.newCachedThreadPool(); final Set<String> used = Sets.newHashSet(); final Set<String> doubleUsed = Sets.newHashSet(); queue = new DistributedQueue<String>(client, consumer, serializer, QUEUE_PATH, QueueBuilder.defaultThreadFactory, executor, Integer.MAX_VALUE, false, "/lock", QueueBuilder.NOT_SET, true, 5000) { @SuppressWarnings("SimplifiableConditionalExpression") @Override protected boolean processWithLockSafety(String itemNode, DistributedQueue.ProcessType type) throws Exception { if (used.contains(itemNode)) { doubleUsed.add(itemNode); } else { used.add(itemNode); } return (client.getState() == CuratorFrameworkState.STARTED) ? super.processWithLockSafety(itemNode, type) : false; } }; queue.start(); for (int i = 0; i < ITERATIONS; ++i) { queue.put(Integer.toString(i)); } Assert.assertTrue(timing.awaitLatch(latch)); Assert.assertTrue(doubleUsed.size() == 0, doubleUsed.toString()); } finally { IOUtils.closeQuietly(queue); IOUtils.closeQuietly(client); } }
From source file:com.fusesource.forge.jmstest.tests.simple.SimpleConsumer.java
protected void run() { Connection con = null;//from w w w. ja v a 2 s . co m Session session = null; final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE); try { con = getConnection(); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = getDestinationProvider().getDestination(session, "queue:TEST"); MessageConsumer consumer = session.createConsumer(dest); consumer.setMessageListener(new MessageListener() { public void onMessage(Message msg) { String grp = null; long nr = 0L; try { grp = msg.getStringProperty("JMSXGroupID"); nr = msg.getLongProperty("MsgNr"); } catch (JMSException jme) { } log().info("Received Message Group=(" + grp + ") MsgNr=" + nr); latch.countDown(); } }); con.start(); latch.await(); con.close(); } catch (Exception e) { } finally { if (con != null) { try { con.close(); } catch (Exception e) { } } } }
From source file:org.killbill.queue.DefaultQueueLifecycle.java
@Override public boolean startQueue() { if (config.isProcessingOff() || !isStarted.compareAndSet(false, true)) { return false; }//from w w w . ja va2s . c o 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:com.googlecode.ehcache.annotations.integration.SelfPopulatingTest.java
/** * Verify that setting selfPopulating=true will guarantee only 1 invocation * of the cached method./*from w w w. ja v a2 s. c om*/ * * @throws Exception */ @Test(timeout = 1000) public void testSelfPopulatingTrue() throws Exception { final CountDownLatch threadRunningLatch = new CountDownLatch(5); final CountDownLatch proccedLatch = new CountDownLatch(1); this.selfPopulatingTestInterface.setThreadRunningLatch(threadRunningLatch); this.selfPopulatingTestInterface.setProccedLatch(proccedLatch); Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingAInvocationCount()); Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingBInvocationCount()); final ThreadGroupRunner threadGroup = new ThreadGroupRunner("testSelfPopulatingFalse-", true); // set up threads threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingA("test2"); } }); threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingA("test2"); } }); threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingB("test2"); } }); threadGroup.addTask(new Runnable() { public void run() { threadRunningLatch.countDown(); selfPopulatingTestInterface.blockingB("test2"); } }); threadGroup.start(); // wait for all threads to get going threadRunningLatch.await(); Thread.sleep(100); // Let both threads complete proccedLatch.countDown(); threadGroup.join(); // verify only 1 call between method A and method B Assert.assertEquals(1, this.selfPopulatingTestInterface.getBlockingAInvocationCount() + this.selfPopulatingTestInterface.getBlockingBInvocationCount()); }
From source file:com.vmware.photon.controller.api.client.resource.DeploymentApiTest.java
@Test public void testGetVmsAsyncForPagination() throws IOException, InterruptedException { Vm vm1 = new Vm(); vm1.setId("vm1"); Vm vm2 = new Vm(); vm2.setId("vm2"); Vm vm3 = new Vm(); vm3.setId("vm3"); String nextPageLink = "nextPageLink"; final ResourceList<Vm> vmList = new ResourceList<>(Arrays.asList(vm1, vm2), nextPageLink, null); final ResourceList<Vm> vmListNextPage = new ResourceList<>(Arrays.asList(vm3)); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(vmList); String serializedTaskNextPage = mapper.writeValueAsString(vmListNextPage); setupMocksForPagination(serializedTask, serializedTaskNextPage, nextPageLink, HttpStatus.SC_OK); DeploymentApi deploymentApi = new DeploymentApi(restClient); final CountDownLatch latch = new CountDownLatch(1); deploymentApi.getAllDeploymentVmsAsync("foo", new FutureCallback<ResourceList<Vm>>() { @Override/*from w ww.ja va2 s .c o m*/ public void onSuccess(ResourceList<Vm> result) { assertEquals(result.getItems().size(), vmList.getItems().size() + vmListNextPage.getItems().size()); assertTrue(result.getItems().containsAll(vmList.getItems())); assertTrue(result.getItems().containsAll(vmListNextPage.getItems())); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }
From source file:com.vmware.photon.controller.api.client.resource.DeploymentRestApiTest.java
@Test public void testGetVmsAsyncForPagination() throws IOException, InterruptedException { Vm vm1 = new Vm(); vm1.setId("vm1"); Vm vm2 = new Vm(); vm2.setId("vm2"); Vm vm3 = new Vm(); vm3.setId("vm3"); String nextPageLink = "nextPageLink"; final ResourceList<Vm> vmList = new ResourceList<>(Arrays.asList(vm1, vm2), nextPageLink, null); final ResourceList<Vm> vmListNextPage = new ResourceList<>(Arrays.asList(vm3)); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(vmList); String serializedTaskNextPage = mapper.writeValueAsString(vmListNextPage); setupMocksForPagination(serializedTask, serializedTaskNextPage, nextPageLink, HttpStatus.SC_OK); DeploymentApi deploymentApi = new DeploymentRestApi(restClient); final CountDownLatch latch = new CountDownLatch(1); deploymentApi.getAllDeploymentVmsAsync("foo", new FutureCallback<ResourceList<Vm>>() { @Override// w w w .j a va 2 s .c o m public void onSuccess(ResourceList<Vm> result) { assertEquals(result.getItems().size(), vmList.getItems().size() + vmListNextPage.getItems().size()); assertTrue(result.getItems().containsAll(vmList.getItems())); assertTrue(result.getItems().containsAll(vmListNextPage.getItems())); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }
From source file:org.elasticsearch.client.RestClientIntegTests.java
public void testAsyncRequests() throws Exception { int numRequests = randomIntBetween(5, 20); final CountDownLatch latch = new CountDownLatch(numRequests); final List<TestResponse> responses = new CopyOnWriteArrayList<>(); for (int i = 0; i < numRequests; i++) { final String method = RestClientTestUtil.randomHttpMethod(getRandom()); final int statusCode = randomStatusCode(getRandom()); restClient.performRequestAsync(method, "/" + statusCode, new ResponseListener() { @Override/*from w w w . j a v a 2 s. co m*/ public void onSuccess(Response response) { responses.add(new TestResponse(method, statusCode, response)); latch.countDown(); } @Override public void onFailure(Exception exception) { responses.add(new TestResponse(method, statusCode, exception)); latch.countDown(); } }); } assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(numRequests, responses.size()); for (TestResponse response : responses) { assertEquals(response.method, response.getResponse().getRequestLine().getMethod()); assertEquals(response.statusCode, response.getResponse().getStatusLine().getStatusCode()); } }
From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java
/** * pullOneThread takes in a thread ID and then * returns all comments that contain that thread ID * @param threadId/*w w w . j a va2 s. c o m*/ * @return * @throws InterruptedException */ public static ArrayList<Comment> pullOneThread(final String threadId) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final ArrayList<Comment> commentList = new ArrayList<Comment>(); if (GSON == null) constructGson(); Thread thread = new Thread() { @Override public void run() { HttpClient client = new DefaultHttpClient(); try { HttpPost searchRequest = new HttpPost(searchAddress); String query = "{\"query\" : {\"query_string\" : {\"default_field\" : \"threadId\", \"query\" : \"" + threadId + "\"}}}"; StringEntity stringentity = new StringEntity(query); searchRequest.setEntity(stringentity); HttpResponse response = client.execute(searchRequest); String json = getEntityContent(response); Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<Comment>>() { }.getType(); ElasticSearchSearchResponse<Comment> esResponse = GSON.fromJson(json, elasticSearchSearchResponseType); for (ElasticSearchResponse<Comment> r : esResponse.getHits()) { Comment topComment = r.getSource(); commentList.add(topComment); } // Sort by latest dated element. Collections.sort(commentList); latch.countDown(); } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); latch.await(); return commentList; }
From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedReentrantLockTest.java
@Test protected void test_try_lock() { ExecutorService exeucotr = Executors.newCachedThreadPool(); final int count = 50; final CountDownLatch latch = new CountDownLatch(count); final DistributedReentrantLock lock = new DistributedReentrantLock(dir); for (int i = 0; i < count; i++) { exeucotr.submit(new Runnable() { public void run() { try { while (lock.tryLock() == false) { Thread.sleep(100 + RandomUtils.nextInt(100)); }// w ww . ja v a 2 s. c o m System.out.println("id: " + lock.getId() + " is leader: " + lock.isOwner()); } catch (InterruptedException e) { want.fail(); } catch (KeeperException e) { want.fail(); } finally { latch.countDown(); try { lock.unlock(); } catch (KeeperException e) { want.fail(); } } } }); } try { latch.await(); } catch (InterruptedException e) { want.fail(); } exeucotr.shutdown(); }
From source file:com.netflix.curator.framework.recipes.locks.TestReaper.java
@Test public void testUsingLeader() throws Exception { final Timing timing = new Timing(); final CuratorFramework client = makeClient(timing, null); final CountDownLatch latch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override//from w w w . j ava2s . co m public void takeLeadership(CuratorFramework client) throws Exception { Reaper reaper = new Reaper(client, 1); try { reaper.addPath("/one/two/three", Reaper.Mode.REAP_UNTIL_DELETE); reaper.start(); timing.sleepABit(); latch.countDown(); } finally { IOUtils.closeQuietly(reaper); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; LeaderSelector selector = new LeaderSelector(client, "/leader", listener); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); selector.start(); timing.awaitLatch(latch); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { IOUtils.closeQuietly(selector); IOUtils.closeQuietly(client); } }