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:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java

@Test
public void testThatDowngradingRespectsThreads() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {//  w  w w. j a  va2s .  c om
        client.start();

        final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");
        ExecutorService t1 = Executors.newSingleThreadExecutor();
        ExecutorService t2 = Executors.newSingleThreadExecutor();

        final CountDownLatch latch = new CountDownLatch(1);

        Future<Object> f1 = t1.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                lock.writeLock().acquire();
                latch.countDown();
                return null;
            }
        });

        Future<Object> f2 = t2.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
                Assert.assertFalse(lock.readLock().acquire(5, TimeUnit.SECONDS));
                return null;
            }
        });

        f1.get();
        f2.get();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.microsoft.office.core.EventsAsyncTestCase.java

private void readAndCheck() throws Exception {
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getEvents().getAsync(event.getId()), new FutureCallback<IEvent>() {
        @Override/*from   w  ww .java2s  . c o m*/
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IEvent result) {
            try {
                event = result;
                Class<?> cls = event.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceEvent.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(getter.invoke(event), property.getPrimitiveValue().toValue());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:com.test.sharksharding.util.sequence.GetMysqlSequenceId2Test.java

/**
 * ???SequenceId//  w  ww . ja v a2s  .  co m
 * 
 * @author gaoxianglong
 */
public @Test void getSequenceId3() {
    final CountDownLatch count = new CountDownLatch(2);
    final List<Long> id1 = new ArrayList<Long>();
    final List<Long> id2 = new ArrayList<Long>();
    final int size = 10000;
    new Thread() {
        public void run() {
            for (int i = 0; i < size; i++) {
                id1.add(SequenceIDManger.getSequenceId(100, 10, 5000));
            }
            count.countDown();
        }
    }.start();
    new Thread() {
        public void run() {
            for (int i = 0; i < size; i++) {
                id2.add(SequenceIDManger.getSequenceId(100, 10, 5000));
            }
            count.countDown();
        }
    }.start();
    try {
        count.await();
        Assert.assertFalse(id1.containsAll(id2));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.opentracing.contrib.elasticsearch5.TracingTest.java

@Test
public void restClient() throws Exception {
    RestClient restClient = RestClient.builder(new HttpHost("localhost", HTTP_PORT, "http"))
            .setHttpClientConfigCallback(new TracingHttpClientConfigCallback(mockTracer)).build();

    HttpEntity entity = new NStringEntity(
            "{\n" + "    \"user\" : \"kimchy\",\n" + "    \"post_date\" : \"2009-11-15T14:12:12\",\n"
                    + "    \"message\" : \"trying out Elasticsearch\"\n" + "}",
            ContentType.APPLICATION_JSON);

    Response indexResponse = restClient.performRequest("PUT", "/twitter/tweet/1",
            Collections.<String, String>emptyMap(), entity);

    assertNotNull(indexResponse);//from  w w  w . j a  v  a 2s  . c  om

    final CountDownLatch latch = new CountDownLatch(1);
    restClient.performRequestAsync("PUT", "/twitter/tweet/2", Collections.<String, String>emptyMap(), entity,
            new ResponseListener() {
                @Override
                public void onSuccess(Response response) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    latch.countDown();
                }
            });

    latch.await(30, TimeUnit.SECONDS);
    restClient.close();

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(2, finishedSpans.size());
    checkSpans(finishedSpans, "PUT");
    assertNull(mockTracer.activeSpan());
}

From source file:com.microsoft.office.core.FolderAsyncTestCase.java

private void createAndCheck() throws Exception {
    prepareFolder();/*from   ww  w.j av  a 2  s .c o  m*/
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                assertTrue(StringUtils.isNotEmpty(folder.getId()));
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

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

@Test
public void should_insert_async() throws Exception {
    //Given/*from   www . j  a  v  a 2 s.  c  o  m*/
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final Date date = new Date();
    final SimpleEntity entity = new SimpleEntity(id, date, "value");
    final CountDownLatch latch = new CountDownLatch(1);
    final CassandraLogAsserter logAsserter = new CassandraLogAsserter();
    logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n");

    //When
    manager.crud().insert(entity).withResultSetAsyncListener(rs -> {
        LOGGER.info(CALLED);
        latch.countDown();
        return rs;
    }).executeAsync();

    //Then
    latch.await();
    logAsserter.assertContains("Called - [achilles-default-executor");

    final List<Row> rows = session.execute("SELECT * FROM simple WHERE id = " + id).all();
    assertThat(rows).hasSize(1);

    final Row row = rows.get(0);
    assertThat(row.getLong("id")).isEqualTo(id);
    assertThat(row.getTimestamp("date")).isEqualTo(date);
    assertThat(row.getString("value")).isEqualTo("value");
}

From source file:io.fabric8.tooling.archetype.commands.ArchetypeCreateAction.java

/**
 * Fetches archetype from the configured repositories
 * TODO: make this code available to hawt.io/JMX too
 *
 * @param archetype/* w  w  w  .j  a  v a2s  . c o m*/
 * @return
 */
private InputStream fetchArchetype(Archetype archetype) throws IOException {
    MavenConfigurationImpl config = new MavenConfigurationImpl(
            new PropertiesPropertyResolver(System.getProperties()), "org.ops4j.pax.url.mvn");
    config.setSettings(new MavenSettingsImpl(config.getSettingsFileUrl(), config.useFallbackRepositories()));
    DownloadManager dm = new DownloadManager(config, Executors.newSingleThreadExecutor());

    final CountDownLatch latch = new CountDownLatch(1);
    DownloadFuture df = dm.download(
            String.format("mvn:%s/%s/%s", archetype.groupId, archetype.artifactId, archetype.version));
    df.addListener(new FutureListener<DownloadFuture>() {
        @Override
        public void operationComplete(DownloadFuture future) {
            latch.countDown();
        }
    });

    try {
        latch.await(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("Failed to download " + archetype);
        throw new IOException(e.getMessage(), e);
    }
    System.out.println("Downloaded archetype (" + df.getFile() + ")");

    return new FileInputStream(df.getFile());
}

From source file:reactor.ipc.netty.tcp.TcpServerTests.java

@Test
public void testIssue462() throws InterruptedException {

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    NettyContext server = TcpServer.create(0).newHandler((in, out) -> {
        in.receive().log("channel").subscribe(trip -> {
            countDownLatch.countDown();
        });// ww w  . j av  a 2 s . com
        return Flux.never();
    }).block(Duration.ofSeconds(30));

    System.out.println("PORT +" + server.address().getPort());

    NettyContext client = TcpClient.create(server.address().getPort())
            .newHandler((in, out) -> out.sendString(Flux.just("test"))).block(Duration.ofSeconds(30));

    client.dispose();
    server.dispose();

    assertThat("countDownLatch counted down", countDownLatch.await(5, TimeUnit.SECONDS));
}

From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java

@Test
public void testRebuildAgainstOtherProcesses() throws Exception {
    NodeCache cache = null;//from w  ww . j  a  v  a 2  s . c o  m
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    client.start();
    try {
        client.create().forPath("/test");
        client.create().forPath("/test/snafu", "original".getBytes());

        final CountDownLatch latch = new CountDownLatch(1);
        cache = new NodeCache(client, "/test/snafu");
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                latch.countDown();
            }
        });
        cache.rebuildTestExchanger = new Exchanger<Object>();

        ExecutorService service = Executors.newSingleThreadExecutor();
        final NodeCache finalCache = cache;
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                // simulate another process updating the node while we're rebuilding
                client.setData().forPath("/test/snafu", "other".getBytes());

                ChildData currentData = finalCache.getCurrentData();
                Assert.assertNotNull(currentData);

                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                return null;
            }
        });
        cache.start(false);
        future.get();

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNotNull(cache.getCurrentData());
        Assert.assertEquals(cache.getCurrentData().getData(), "other".getBytes());
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:io.fabric8.agent.DownloadManagerTest.java

@Test
public void testDownloadAlreadyDownloadedArtifact() throws Exception {
    DownloadManager dm = createDownloadManager("non-existing-settings.xml", null);
    File dir = new File(systemRepo, "x/y/z/1.0");
    dir.mkdirs();//from ww  w . ja  va  2  s . c  o m
    FileOutputStream artifact = new FileOutputStream(new File(dir, "z-1.0.jar"));
    artifact.write(new byte[] { 0x42 });
    artifact.close();

    final CountDownLatch latch = new CountDownLatch(1);
    DownloadFuture df = dm.download("mvn:x.y/z/1.0");
    df.addListener(new FutureListener<DownloadFuture>() {
        @Override
        public void operationComplete(DownloadFuture future) {
            latch.countDown();
        }
    });

    latch.await(30, TimeUnit.SECONDS);
    assertNotNull(df.getUrl());
    assertNotNull(df.getFile());
    assertEquals("z-1.0.jar", df.getFile().getName());
    LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile());
}