Example usage for java.util.concurrent CountDownLatch countDown

List of usage examples for java.util.concurrent CountDownLatch countDown

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch countDown.

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

From source file:info.archinnov.achilles.it.TestAsyncDSLSimpleEntity.java

@Test
public void should_dsl_select_slice_async() throws Exception {
    //Given/*from  w  ww  .  jav  a 2  s  .  c om*/
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id", id);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    final Date date1 = dateFormat.parse("2015-10-01 00:00:00 GMT");
    final Date date9 = dateFormat.parse("2015-10-09 00:00:00 GMT");
    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");
    values.put("date6", "'2015-10-06 00:00:00+0000'");
    values.put("date7", "'2015-10-07 00:00:00+0000'");
    values.put("date8", "'2015-10-08 00:00:00+0000'");
    values.put("date9", "'2015-10-09 00:00:00+0000'");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_many_rows.cql", values);

    final CountDownLatch latch = new CountDownLatch(1);
    final CassandraLogAsserter logAsserter = new CassandraLogAsserter();
    logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n");

    //When
    final CompletableFuture<List<SimpleEntity>> future = manager.dsl().select().consistencyList().simpleSet()
            .simpleMap().value().simpleMap().fromBaseTable().where().id_Eq(id).date_Gte_And_Lt(date1, date9)
            .withResultSetAsyncListener(rs -> {
                LOGGER.info(CALLED);
                latch.countDown();
                return rs;
            }).withTracing().getListAsync();

    //Then
    latch.await();
    assertThat(future.get()).hasSize(8);
    logAsserter.assertContains("Called - [achilles-default-executor");
}

From source file:com.datatorrent.contrib.hdht.HDHTWriterTest.java

@Test
public void testWriteError() throws Exception {
    File file = new File(testInfo.getDir());
    FileUtils.deleteDirectory(file);//from  ww  w  .  j  a va 2s .co m

    final RuntimeException writeError = new RuntimeException("failure simulation");
    final CountDownLatch endWindowComplete = new CountDownLatch(1);
    final CountDownLatch writerActive = new CountDownLatch(1);

    FileAccessFSImpl fa = new MockFileAccess() {
        @Override
        public FileWriter getWriter(long bucketKey, String fileName) throws IOException {
            writerActive.countDown();
            try {
                if (endWindowComplete.await(10, TimeUnit.SECONDS)) {
                    throw writeError;
                }
            } catch (InterruptedException e) {
                //Do nothing
            }
            return super.getWriter(bucketKey, fileName);
        }
    };
    fa.setBasePath(file.getAbsolutePath());
    HDHTWriter hds = new HDHTWriter();
    hds.setFileStore(fa);
    hds.setFlushIntervalCount(0); // flush after every window

    long BUCKETKEY = 1;

    hds.setup(new OperatorContextTestHelper.TestIdOperatorContext(0, new DefaultAttributeMap()));
    //hds.writeExecutor = new ScheduledThreadPoolExecutor(1);

    hds.beginWindow(1);
    long[] seqArray = { 5L, 1L, 3L, 4L, 2L };
    for (long seq : seqArray) {
        Slice key = newKey(BUCKETKEY, seq);
        hds.put(BUCKETKEY, key, ("data" + seq).getBytes());
    }
    hds.endWindow();
    hds.checkpointed(1);
    hds.committed(1);
    endWindowComplete.countDown();

    try {
        Assert.assertTrue(writerActive.await(10, TimeUnit.SECONDS));
        hds.writeExecutor.shutdown();
        hds.writeExecutor.awaitTermination(10, TimeUnit.SECONDS);
        hds.beginWindow(2);
        hds.endWindow();
        Assert.fail("exception not raised");
    } catch (Exception e) {
        Assert.assertSame(writeError, e.getCause());
    }

    hds.teardown();
}

From source file:com.dangdang.ddframe.job.api.type.dataflow.executor.DataflowJobExecutor.java

private Map<Integer, List<Object>> fetchDataForSequence(final ShardingContext shardingContext) {
    Collection<Integer> items = shardingContext.getShardingItemParameters().keySet();
    final Map<Integer, List<Object>> result = new ConcurrentHashMap<>(items.size());
    final CountDownLatch latch = new CountDownLatch(items.size());
    for (final int each : items) {
        getExecutorService().submit(new Runnable() {

            @Override/* w  ww.  j a va 2  s  .c om*/
            public void run() {
                try {
                    List<Object> data = dataflowJob.fetchData(shardingContext.getShardingContext(each));
                    if (null != data && !data.isEmpty()) {
                        result.put(each, data);
                    }
                } finally {
                    latch.countDown();
                }
            }
        });
    }
    latchAwait(latch);
    JobEventBus.getInstance().post(new JobTraceEvent(getJobName(), LogLevel.TRACE,
            String.format("Fetch data size: '%s'.", result.size())));
    return result;
}

From source file:com.frostwire.android.tests.vuze.VuzeDownloadTest.java

@LargeTest
public void testDownload1() throws IOException, TOTorrentException {

    HttpClient c = HttpClientFactory.newInstance();

    File torrentFile = new File(SystemUtils.getTorrentsDirectory(), "download_test1.torrent");
    File saveDir = SystemUtils.getTorrentDataDirectory();
    c.save(TorrentUrls.FROSTCLICK_BRANDON_HINES_2010, torrentFile);

    TOTorrent t = readTorrent(torrentFile.getAbsolutePath());

    VuzeUtils.remove(t.getHash(), true);
    TestUtils.sleep(10000);//from  w w w .  j  a v  a2s  .c om

    final CountDownLatch signal = new CountDownLatch(1);

    VuzeDownloadManager dm = VuzeDownloadFactory.create(torrentFile.getAbsolutePath(), null,
            saveDir.getAbsolutePath(), new VuzeDownloadListener() {

                @Override
                public void stateChanged(VuzeDownloadManager dm, int state) {
                    LOG.info("testDownload1-stateChanged:" + formatDownloadState(state));
                }

                @Override
                public void downloadComplete(VuzeDownloadManager dm) {
                    signal.countDown();
                }
            });

    assertNotNull(dm);

    assertTrue("Download not finished", TestUtils.await(signal, 1, TimeUnit.HOURS));
}

From source file:com.sixt.service.framework.kafka.KafkaThrottlingTest.java

@Test
public void throttleTest() throws InterruptedException {
    int messageCount = 200;
    CountDownLatch latch = new CountDownLatch(messageCount);

    DockerPort kafka = docker.containers().container("kafka").port(9092);
    ServiceProperties props = new ServiceProperties();
    props.addProperty(KAFKA_SERVER_KEY, kafka.inFormat("$HOST:$EXTERNAL_PORT"));

    String topic = "throttle-test";
    KafkaPublisherFactory publisherFactory = new KafkaPublisherFactory(props);
    KafkaPublisher publisher = publisherFactory.newBuilder(topic).build();

    KafkaSubscriberFactory subscriberFactory = new KafkaSubscriberFactory<String>(props);
    EventReceivedCallback<String> callback = (message, topicInfo) -> {
        latch.countDown();
        try {/*from   w  w w .  j  a  va 2s  .c  o  m*/
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };
    //noinspection unchecked
    subscriberFactory.newBuilder(topic, callback).withPollTime(50).withAutoCommit(true).build();

    for (int i = 0; i < messageCount; i++) {
        publisher.publishSync("message " + i + randomData());
    }
    latch.await();
}

From source file:zipkin.execjar.ExecJarRule.java

@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {
        public void evaluate() throws Throwable {
            try {
                ProcessBuilder bootBuilder = new ProcessBuilder("java", "-jar", execJar);
                bootBuilder.environment().put("SERVER_PORT", String.valueOf(port()));
                bootBuilder.environment().putAll(environment);
                bootBuilder.redirectErrorStream(true);
                bootApp = bootBuilder.start();

                CountDownLatch startedOrCrashed = new CountDownLatch(1);
                Thread consoleReader = new Thread(() -> {
                    boolean foundStartMessage = false;
                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(bootApp.getInputStream()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.indexOf("JVM running for") != -1) {
                                foundStartMessage = true;
                                startedOrCrashed.countDown();
                            }/*ww w . j  a  v a  2  s.  c om*/
                            console.add(line);
                        }
                    } catch (Exception e) {
                    } finally {
                        if (!foundStartMessage)
                            startedOrCrashed.countDown();
                    }
                });
                consoleReader.setDaemon(true);
                consoleReader.start();

                if (!startedOrCrashed.await(10, TimeUnit.SECONDS)) {
                    throw new AssumptionViolatedException("Took too long to start or crash");
                }

                base.evaluate();
            } finally {
                bootApp.destroy();
            }
        }
    };
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_update_interceptors() throws Exception {

    CompleteBean entity = builder().randomId().buid();

    final CountDownLatch latch = new CountDownLatch(2);
    final AchillesFuture<CompleteBean> future = asyncManager.insert(entity,
            withAsyncListeners(new FutureCallback<Object>() {
                @Override//from   ww w .  j  a  v  a2  s.co  m
                public void onSuccess(Object result) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable t) {

                }
            }));

    entity = future.get();
    entity.setName("DuyHai");
    entity.setLabel("label");

    asyncManager.update(entity, withAsyncListeners(new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {

        }
    }));

    latch.await();

    Row row = session.execute("select name,label from CompleteBean where id = " + entity.getId()).one();

    assertThat(row.getString("name")).isEqualTo("preUpdate");
    assertThat(row.getString("label")).isEqualTo("label");
    assertThat(entity.getName()).isEqualTo("preUpdate");
    assertThat(entity.getLabel()).isEqualTo("postUpdate");
}

From source file:io.druid.server.namespace.cache.NamespaceExtractionCacheManagerExecutorsTest.java

@Test(timeout = 50_000)
public void testConcurrentDelete() throws ExecutionException, InterruptedException {
    final int threads = 5;
    ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(threads));
    final CountDownLatch latch = new CountDownLatch(threads);
    Collection<ListenableFuture<?>> futures = new ArrayList<>();
    for (int i = 0; i < threads; ++i) {
        final int loopNum = i;
        ListenableFuture<?> future = executorService.submit(new Runnable() {
            @Override/*w ww  .  j  av a 2  s  .com*/
            public void run() {
                try {
                    latch.countDown();
                    latch.await();
                    for (int j = 0; j < 10; ++j) {
                        testDelete(String.format("ns-%d", loopNum));
                    }
                } catch (InterruptedException e) {
                    throw Throwables.propagate(e);
                }
            }
        });
    }
    Futures.allAsList(futures).get();
    executorService.shutdown();
}

From source file:org.apache.cxf.systest.jaxrs.AbstractJAXRSContinuationsTest.java

protected void doTestContinuation(String pathSegment) throws Exception {
    final String port = getPort();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);
    List<BookWorker> workers = new ArrayList<>(5);
    for (int x = 1; x < 6; x++) {
        workers.add(new BookWorker("http://localhost:" + port + getBaseAddress() + pathSegment + "/" + x,
                Integer.toString(x), "CXF in Action" + x, startSignal, doneSignal));
    }//from w w  w  . jav a2s  .c o  m
    for (BookWorker w : workers) {
        executor.execute(w);
    }

    startSignal.countDown();
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
    for (BookWorker w : workers) {
        w.checkError();
    }
}

From source file:com.vmware.photon.controller.api.client.resource.FlavorApiTest.java

@Test
public void testListAllAsyncForPagination() throws Exception {
    Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    Flavor flavor2 = new Flavor();
    flavor2.setId("flavor2");
    flavor2.setKind("vm");

    Flavor flavor3 = new Flavor();
    flavor3.setId("flavor3");
    flavor3.setKind("vm");

    String nextPageLink = "nextPageLink";

    final ResourceList<Flavor> flavorResourceList = new ResourceList<>(Arrays.asList(flavor1, flavor2),
            nextPageLink, null);/*ww w.  j a  v a 2  s .com*/
    final ResourceList<Flavor> flavorResourceListNextPage = new ResourceList<>(Arrays.asList(flavor3));
    final ResourceList<Flavor> expectedFlavorResourceList = new ResourceList<>(
            Arrays.asList(flavor1, flavor2, flavor3));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavorResourceList);
    String serializedResponseNextPage = mapper.writeValueAsString(flavorResourceListNextPage);

    setupMocksForPagination(serializedResponse, serializedResponseNextPage, nextPageLink, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.listAllAsync(new FutureCallback<ResourceList<Flavor>>() {
        @Override
        public void onSuccess(@Nullable ResourceList<Flavor> result) {
            assertTrue(result.getItems().containsAll(expectedFlavorResourceList.getItems()));
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}