List of usage examples for java.util.concurrent CountDownLatch await
public void await() throws InterruptedException
From source file:com.onyxscheduler.domain.SchedulerIT.java
private void waitJobWithPastDate() throws Scheduler.DuplicateJobKeyException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); latchProvider.setLatch(latch);/*w w w . j a v a 2 s .c o m*/ CountDownJob existingJob = buildJobWithFixedDateTrigger(buildPastDate()); scheduler.scheduleJob(existingJob); latch.await(); }
From source file:com.onyxscheduler.domain.SchedulerIT.java
@Test(timeout = FIRE_THRESHOLD_TIMEOUT_IN_MILLIS) public void shouldFireJobOnceWithPastDate() throws Scheduler.DuplicateJobKeyException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); latchProvider.setLatch(latch);//from w w w. java 2 s .c o m CountDownJob existingJob = buildJobWithFixedDateTrigger(buildPastDate()); scheduler.scheduleJob(existingJob); latch.await(); }
From source file:com.onyxscheduler.domain.SchedulerIT.java
@Test(timeout = FIRE_THRESHOLD_TIMEOUT_IN_MILLIS) public void shouldFireJobOnceWithReachableFutureDate() throws Scheduler.DuplicateJobKeyException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); latchProvider.setLatch(latch);// w w w . j av a 2 s.c o m CountDownJob job = buildJobWithFixedDateTrigger(buildReachableFutureDate()); scheduler.scheduleJob(job); latch.await(); }
From source file:com.alibaba.druid.benckmark.pool.Case2.java
private void p0(final DataSource dataSource, String name, int threadCount) throws Exception { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCount); final AtomicLong blockedStat = new AtomicLong(); final AtomicLong waitedStat = new AtomicLong(); for (int i = 0; i < threadCount; ++i) { Thread thread = new Thread() { public void run() { try { startLatch.await(); long threadId = Thread.currentThread().getId(); long startBlockedCount, startWaitedCount; {//from w w w . ja v a 2s.co m ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId); startBlockedCount = threadInfo.getBlockedCount(); startWaitedCount = threadInfo.getWaitedCount(); } for (int i = 0; i < LOOP_COUNT; ++i) { Connection conn = dataSource.getConnection(); conn.close(); } ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId); long blockedCount = threadInfo.getBlockedCount() - startBlockedCount; long waitedCount = threadInfo.getWaitedCount() - startWaitedCount; blockedStat.addAndGet(blockedCount); waitedStat.addAndGet(waitedCount); } catch (Exception ex) { ex.printStackTrace(); } endLatch.countDown(); } }; thread.start(); } long startMillis = System.currentTimeMillis(); long startYGC = TestUtil.getYoungGC(); long startFullGC = TestUtil.getFullGC(); startLatch.countDown(); endLatch.await(); long millis = System.currentTimeMillis() - startMillis; long ygc = TestUtil.getYoungGC() - startYGC; long fullGC = TestUtil.getFullGC() - startFullGC; System.out.println("thread " + threadCount + " " + name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC + " blockedCount " + blockedStat.get() + " waitedCount " + waitedStat.get()); }
From source file:com.gopivotal.cla.github.RateLimitingClientHttpRequestInterceptorTest.java
@Test public void block() throws InterruptedException, IOException { CountDownLatch latch = new CountDownLatch(1); MockClientHttpRequest request = new MockClientHttpRequest(); MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.OK); ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); request.setMethod(HttpMethod.GET);/*ww w .java2 s. c o m*/ request.setURI(URI.create("http://localhost")); when(execution.execute(request, new byte[0])).thenReturn(response); new Thread(new Trigger(this.interceptor, latch)).start(); latch.await(); this.interceptor.intercept(request, new byte[0], execution); }
From source file:com.googlecode.xmlzen.XmlSlicerTest.java
@Test public void testXmlSlicerListConcurrency() throws Exception { final CountDownLatch latch = new CountDownLatch(SLICER_ITERATIONS); final XmlSlicerList xsl = new XmlSlicerList(); xsl.add(XmlSlicer.cut("1")); xsl.add(XmlSlicer.cut("2")); xsl.add(XmlSlicer.cut("3")); for (int i = 0; i < SLICER_ITERATIONS; i++) { new Thread(new Runnable() { public void run() { assertEquals(Arrays.asList(new String[] { "1", "2", "3" }), xsl.asList()); latch.countDown();/* w w w .j a v a 2 s .c o m*/ } }).start(); } latch.await(); }
From source file:com.basho.riak.client.http.util.logging.ConcurrentLoggingTest.java
/** * Test method for//ww w. j a v a2s . c o m * {@link com.basho.riak.client.http.util.logging.LogNoHttpResponseRetryHandler#retryMethod(org.apache.commons.httpclient.HttpMethod, java.io.IOException, int)} * . * * @throws InterruptedException */ @Test public void retry_concurrentLogAndDump() throws InterruptedException { // create a bunch of threads // each must log 10 statements and call flush // ALL the statements must be present BUT ONCE in // the mock delegate appender (order does not matter) final int numThreads = 10; final LogNoHttpResponseRetryHandler handler = new LogNoHttpResponseRetryHandler(); ExecutorService es = Executors.newFixedThreadPool(numThreads); List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(numThreads); final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch dumpLatch = new CountDownLatch(10); for (int i = 0; i < numThreads; i++) { final int threadCounter = i; tasks.add(new Callable<Void>() { @Override public Void call() { Logger logger = Logger.getLogger("httpclient.wire"); try { startLatch.await(); for (int j = 0; j < 10; j++) { logger.debug(String.format(MESSAGE, new Object[] { threadCounter, j })); } dumpLatch.countDown(); dumpLatch.await(); handler.retryMethod(new GetMethod(), new NoHttpResponseException(), 0); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } }); } startLatch.countDown(); es.invokeAll(tasks); verify(mockLogger, times(100)).callAppenders(logEventCaptor.capture()); TreeSet<Integer> check = new TreeSet<Integer>(); for (LoggingEvent le : logEventCaptor.getAllValues()) { // verify that each of Thread:Iter is present for 0-90-9 int loc = Integer.parseInt(le.getMessage().toString()); check.add(loc); } assertEquals(100, check.size()); assertEquals(0, (int) check.first()); assertEquals(99, (int) check.last()); }
From source file:com.netflix.curator.framework.recipes.queue.TestDistributedPriorityQueue.java
@Test public void testSimple() throws Exception { List<Integer> nums = new ArrayList<Integer>(); Timing timing = new Timing(); DistributedPriorityQueue<Integer> queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start();/*w w w . j av a2 s . co m*/ try { final CountDownLatch hasConsumedLatch = new CountDownLatch(1); final CountDownLatch okToConsumeLatch = new CountDownLatch(1); BlockingQueueConsumer<Integer> consumer = new BlockingQueueConsumer<Integer>( Mockito.mock(ConnectionStateListener.class)) { @Override public void consumeMessage(Integer message) throws Exception { hasConsumedLatch.countDown(); okToConsumeLatch.await(); super.consumeMessage(message); } }; queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0); queue.start(); nums.add(Integer.MIN_VALUE); queue.put(Integer.MIN_VALUE, Integer.MIN_VALUE); // the queue background thread will be blocking with the first item - make sure it's the lowest value Assert.assertTrue(timing.awaitLatch(hasConsumedLatch)); Random random = new Random(); for (int i = 0; i < 100; ++i) { int priority = random.nextInt(); nums.add(priority); queue.put(priority, priority); } while (queue.getCache().getData().children.size() < (nums.size() - 1)) // -1 because the first message has already been consumed { timing.sleepABit(); // wait for the cache to catch up } okToConsumeLatch.countDown(); assertOrdering(consumer, nums.size()); } catch (AssertionError e) { StringBuilder message = new StringBuilder(e.getMessage()); for (int i : nums) { message.append(i).append("\t").append(DistributedPriorityQueue.priorityToString(i)).append("\n"); } Assert.fail(message.toString()); } finally { IOUtils.closeQuietly(queue); IOUtils.closeQuietly(client); } }
From source file:de.hybris.platform.masterserver.impl.DefaultStatisticsGatewayTest.java
@Test public void shouldUpdateLoggedInBackOfficeUsersConcurrently() throws InterruptedException { // given//ww w . j ava 2 s.c om generateStats = true; given(businessCollector.collectStatistics()).willReturn(null); given(systemCollector.collectStatistics()).willReturn(null); given(encryptor.encrypt(eq("{\"session\":{\"backOfficeOverallUsers\":{\"hac\":500}}}"), anyString())) .willReturn(statisticsPayload); final CountDownLatch latch = new CountDownLatch(500); // when for (int i = 0; i < 500; i++) { new Thread(new Runnable() { @Override public void run() { try { statGateway.updateLoggedInUsersStats("/hac"); } finally { latch.countDown(); } } }).start(); } latch.await(); final StatisticsPayload encodedStatistics = statGateway.getStatisticsPayload(); // then assertThat(encodedStatistics).isNotNull(); }
From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java
/** * postThread posts a top comment to Elastic-Search. * Tested and verified.//from w ww.j a va2 s . com * @param ElasticSearchOperations * @throws InterruptedException */ public static void postThread(final Comment commentThread) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); if (GSON == null) constructGson(); Thread thread = new Thread() { @Override public void run() { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(postAddress + commentThread.getUuid() + "/"); try { request.setEntity(new StringEntity(GSON.toJson(commentThread))); HttpResponse response = client.execute(request); Log.w(serverName, response.getStatusLine().toString()); response.getStatusLine().toString(); HttpEntity entity = response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String output = reader.readLine(); while (output != null) { Log.w(serverName, output); output = reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } latch.countDown(); } }; thread.start(); latch.await(); }