List of usage examples for java.util.concurrent CountDownLatch await
public void await() throws InterruptedException
From source file:com.microsoft.office.core.AttachmentsAsyncTestCase.java
private void removeAttachment(final IAttachment attachment) throws Exception { final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback(message.getAttachmentsAsync(), new FutureCallback<IAttachments>() { public void onSuccess(IAttachments attachments) { attachments.delete(attachment.getId()); Me.flush();/*from w w w .j a v a2 s. c o m*/ cdl.countDown(); }; @Override public void onFailure(Throwable err) { reportError(err); cdl.countDown(); } }); cdl.await(); }
From source file:org.cleverbus.core.common.asynch.confirm.ConfirmationPollExecutorTest.java
@Test public void testGetNextMessage_moreThreads() throws InterruptedException { // firstly commit messages to DB (we can commit because we have embedded DB for tests only) TransactionTemplate txTemplate = new TransactionTemplate(jpaTransactionManager); txTemplate.execute(new TransactionCallbackWithoutResult() { @Override/* ww w .j a va2 s. c o m*/ protected void doInTransactionWithoutResult(TransactionStatus status) { Message msg = insertNewMessage("1234_4567"); confirmationService.insertFailedConfirmation(msg); msg = insertNewMessage("1234_4567_8"); confirmationService.insertFailedConfirmation(msg); msg = insertNewMessage("1234_4567_9"); confirmationService.insertFailedConfirmation(msg); } }); // prepare threads int threads = 5; final CountDownLatch latch = new CountDownLatch(threads); Runnable task = new Runnable() { @Override public void run() { try { pollExecutor.run(); } finally { latch.countDown(); } } }; mock.expectedMessageCount(3); // start processing and waits for result for (int i = 0; i < threads; i++) { new Thread(task).start(); } latch.await(); mock.assertIsSatisfied(); // verify messages ExternalCall extCall1 = findConfirmation("1234_4567"); assertThat(extCall1, notNullValue()); assertThat(extCall1.getState(), is(ExternalCallStateEnum.PROCESSING)); ExternalCall extCall2 = findConfirmation("1234_4567_8"); assertThat(extCall2, notNullValue()); assertThat(extCall2.getState(), is(ExternalCallStateEnum.PROCESSING)); ExternalCall extCall3 = findConfirmation("1234_4567_9"); assertThat(extCall3, notNullValue()); assertThat(extCall3.getState(), is(ExternalCallStateEnum.PROCESSING)); // check confirmationService confirmationService.confirmationFailed(extCall1); extCall1 = findConfirmation("1234_4567"); assertThat(extCall1.getState(), is(ExternalCallStateEnum.FAILED)); confirmationService.confirmationComplete(extCall2); extCall2 = findConfirmation("1234_4567_8"); assertThat(extCall2.getState(), is(ExternalCallStateEnum.OK)); }
From source file:info.archinnov.achilles.it.TestAsyncCRUDSimpleEntity.java
@Test public void should_find_by_id_async() throws Exception { //Given// w ww .j av a 2 s. co m final long id = RandomUtils.nextLong(0, Long.MAX_VALUE); scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql", ImmutableMap.of("id", id, "table", "simple")); final Date date = buildDateKey(); final CountDownLatch latch = new CountDownLatch(1); final CassandraLogAsserter logAsserter = new CassandraLogAsserter(); logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n"); //When final CompletableFuture<Tuple2<SimpleEntity, ExecutionInfo>> tuple2 = manager.crud().findById(id, date) .withResultSetAsyncListener(rs -> { LOGGER.info(CALLED); latch.countDown(); return rs; }).getAsyncWithStats(); //Then latch.await(); final SimpleEntity actual = tuple2.get()._1(); final ExecutionInfo executionInfo = tuple2.get()._2(); assertThat(actual).isNotNull(); assertThat(actual.getConsistencyList()).containsExactly(ConsistencyLevel.QUORUM, ConsistencyLevel.LOCAL_ONE); assertThat(executionInfo.getQueriedHost().isUp()).isTrue(); logAsserter.assertContains("Called - [achilles-default-executor"); }
From source file:com.linkedin.pinot.integration.tests.DefaultColumnsClusterIntegrationTest.java
protected void setUp(boolean sendSchema) throws Exception { // Set up directories. FileUtils.deleteQuietly(TMP_DIR);/*from w w w .ja v a 2s. c o m*/ Assert.assertTrue(TMP_DIR.mkdirs()); Assert.assertTrue(SEGMENT_DIR.mkdir()); Assert.assertTrue(TAR_DIR.mkdir()); // Start the cluster. startZk(); startController(); startBroker(); startServer(); // Create the table. addOfflineTable("mytable", "DaysSinceEpoch", "daysSinceEpoch", -1, "", null, null); // Add the schema. if (sendSchema) { sendSchema(); } // Unpack the Avro files. List<File> avroFiles = unpackAvroData(TMP_DIR, SEGMENT_COUNT); // Load data into H2. ExecutorService executor = Executors.newCachedThreadPool(); setupH2AndInsertAvro(avroFiles, executor); // Create segments from Avro data. buildSegmentsFromAvro(avroFiles, executor, 0, SEGMENT_DIR, TAR_DIR, "mytable", false, null); // Initialize query generator. setupQueryGenerator(avroFiles, executor); executor.shutdown(); executor.awaitTermination(10, TimeUnit.MINUTES); // Set up a Helix spectator to count the number of segments that are uploaded and unlock the latch once 12 segments // are online. CountDownLatch latch = setupSegmentCountCountDownLatch("mytable", SEGMENT_COUNT); // Upload the segments. for (String segmentName : TAR_DIR.list()) { File file = new File(TAR_DIR, segmentName); FileUploadUtils.sendSegmentFile("localhost", "8998", segmentName, new FileInputStream(file), file.length()); } // Wait for all segments to be ONLINE. latch.await(); waitForSegmentsOnline(); }
From source file:com.vladmihalcea.mongo.dao.ProductRepositoryIT.java
@Test public void testRetries() throws InterruptedException { Product product = new Product(); product.setId(123L);//from w ww. jav a 2 s . c o m product.setName("Tv"); productRepository.save(product); Product savedProduct = productRepository.findOne(123L); assertEquals(savedProduct, product); final int threadsNumber = 10; final AtomicInteger atomicInteger = new AtomicInteger(); final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1); final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1); for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) { final long index = (long) atomicInteger.get() * threadsNumber; LOGGER.info("Scheduling thread index {}", index); Thread testThread = new Thread(new Runnable() { @Override public void run() { try { startLatch.countDown(); startLatch.await(); productService.updateName(123L, UUID.randomUUID().toString()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { LOGGER.error("Exception thrown!", e); } finally { endLatch.countDown(); } } }); testThread.start(); } startLatch.countDown(); LOGGER.info("Waiting for threads to be done"); endLatch.countDown(); endLatch.await(); LOGGER.info("Threads are done"); }
From source file:org.cleverbus.core.common.asynch.msg.MessageOperationServiceTest.java
@Test public void testRestartForFailedMessage_multiThreaded() throws Exception { // prepare message in FAILED state final Message[] messages = createAndSaveMessages(1, new MessageProcessor() { @Override//from w w w . j a va2 s . c o m public void process(Message message) { message.setState(MsgStateEnum.FAILED); } }); // prepare threads int threads = 2; final CountDownLatch latch = new CountDownLatch(threads); Runnable task = new Runnable() { @Override public void run() { try { // cancel message operationService.restartMessage(messages[0].getMsgId(), false); } finally { latch.countDown(); } } }; // start processing and waits for result for (int i = 0; i < threads; i++) { new Thread(task).start(); } latch.await(); // verify Message msgDB = em.find(Message.class, messages[0].getMsgId()); assertThat(msgDB, notNullValue()); assertThat(msgDB.getState(), is(MsgStateEnum.PARTLY_FAILED)); }
From source file:gda.util.persistence.LocalParametersTest.java
public void testThreadSafety() throws Exception { final File testScratchDir = TestUtils.createClassScratchDirectory(LocalParametersTest.class); final String configDir = testScratchDir.getAbsolutePath(); final String configName = "threadsafety"; // Delete config from disk, if it exists final File configFile = new File(configDir, configName + ".xml"); configFile.delete();//w w w . j av a2 s. c o m final AtomicReference<Exception> error = new AtomicReference<Exception>(); final int numThreads = 4; final long threadRunTimeInMs = 5000; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch finishLatch = new CountDownLatch(numThreads); for (int i = 0; i < numThreads; i++) { Thread t = new Thread() { @Override public void run() { try { final FileConfiguration config = LocalParameters.getThreadSafeXmlConfiguration(configDir, configName, true); // Wait for signal to start startLatch.await(); final String propertyName = Thread.currentThread().getName(); final long startTime = System.currentTimeMillis(); while (true) { // Finish if we've exceeded the run time long elapsedTime = System.currentTimeMillis() - startTime; if (elapsedTime >= threadRunTimeInMs) { break; } // Finish if another thread has generated an exception if (error.get() != null) { break; } config.setProperty(propertyName, System.currentTimeMillis()); config.save(); } } catch (Exception e) { e.printStackTrace(System.err); error.set(e); } finishLatch.countDown(); } }; t.start(); } // Start all threads final long startTime = System.currentTimeMillis(); startLatch.countDown(); // Wait for all threads to finish finishLatch.await(); final long endTime = System.currentTimeMillis(); final long elapsedTime = (endTime - startTime); System.out.printf("Finished after %dms%n", elapsedTime); // No error should have been thrown assertNull("An exception was thrown by one of the threads", error.get()); }
From source file:com.brienwheeler.apps.main.ContextMainTest.java
@Test public void testContextReuse() throws InterruptedException { PropertiesTestUtils.clearAllTestSystemProperties(); Assert.assertNull(System.getProperty(TestDataConstants.RMAP_TEST_PROP)); CountDownLatch latch = new CountDownLatch(1); TestContextMain main = new TestContextMain( new String[] { C, TestDataConstants.RMAP_CTX_DIRECT, C, TestDataConstants.RMAP_CTX_INDIRECT }, latch);/*from w w w . j a v a2s. c o m*/ TestRunner testRunner = new TestRunner(main); testRunner.start(); latch.await(); Assert.assertEquals(TestDataConstants.RMAP_TEST_VAL, System.getProperty(TestDataConstants.RMAP_TEST_PROP)); assertLaunchCount(main, 1); main.shutdown(); testRunner.join(); }
From source file:com.brienwheeler.apps.main.ContextMainTest.java
@Test public void testContextWithNoPropsMap() throws InterruptedException { PropertiesTestUtils.clearAllTestSystemProperties(); Assert.assertNull(System.getProperty(TestDataConstants.PROPS_FILE1_PROP)); CountDownLatch latch = new CountDownLatch(1); TestContextMain main = new TestContextMain( new String[] { M, TestDataConstants.RMAP2_LOCATION, C, TestDataConstants.RMAP_CTX_WITH_PROPS }, latch);//from ww w .ja va 2 s . c o m TestRunner testRunner = new TestRunner(main); testRunner.start(); latch.await(); assertLaunchCount(main, 1); main.shutdown(); testRunner.join(); Assert.assertEquals(TestDataConstants.PROPS_FILE1_VALUE, System.getProperty(TestDataConstants.PROPS_FILE1_PROP)); }
From source file:com.onyxscheduler.domain.SchedulerIT.java
@Test(timeout = FIRE_THRESHOLD_TIMEOUT_IN_MILLIS) public void shouldFireMultipleTimesWithTwoPastTriggers() throws Scheduler.DuplicateJobKeyException, InterruptedException { CountDownLatch latch = new CountDownLatch(2); latchProvider.setLatch(latch);/*from w ww .j av a 2s . c o m*/ Instant pastDate = buildPastDate(); CountDownJob job = CountDownJob.buildFromTriggers( ImmutableSet.of(Trigger.fromFixedTime(pastDate), Trigger.fromFixedTime(pastDate.plusSeconds(1)))); scheduler.scheduleJob(job); latch.await(); }