Example usage for java.util.concurrent CountDownLatch CountDownLatch

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

Introduction

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

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

From source file:com.github.dozermapper.core.DozerBeanMapperTest.java

@Test
public void shouldBeThreadSafe() throws Exception {
    Mapper mapper = DozerBeanMapperBuilder.create().withMappingFiles("mappings/testDozerBeanMapping.xml")
            .build();//ww w. j  a  v  a 2  s  . c  o  m

    final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);

    for (int i = 0; i < THREAD_COUNT; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    mapper.map(new TestObject(), TestObjectPrime.class);
                } finally {
                    latch.countDown();
                }
            }
        }).start();

    }
    latch.await();
    assertTrue(exceptions.isEmpty());
}

From source file:com.github.oscerd.component.cassandra.embedded.CassandraBaseTest.java

@Override
public void doPostSetup() {
    String id = RandomStringUtils.random(12, "0123456789abcdefghijklmnopqrstuvwxyz");
    fs = new Farsandra();
    fs.withVersion("2.0.3");
    fs.withCleanInstanceOnStart(true);/*  ww  w. j a v a2s . c o m*/
    fs.withInstanceName("target" + File.separator + id);
    fs.withCreateConfigurationFiles(true);
    fs.withHost("localhost");
    fs.withSeeds(Arrays.asList("localhost"));
    final CountDownLatch started = new CountDownLatch(1);
    fs.getManager().addOutLineHandler(new LineHandler() {
        @Override
        public void handleLine(String line) {
            if (line.contains("Listening for thrift clients...")) {
                started.countDown();
            }
        }
    });
    fs.getManager().addProcessHandler(new ProcessHandler() {
        @Override
        public void handleTermination(int exitValue) {
            started.countDown();
        }
    });
    fs.start();
    try {
        started.await();
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect();
    session.execute("CREATE KEYSPACE IF NOT EXISTS simplex WITH replication "
            + "= {'class':'SimpleStrategy', 'replication_factor':3};");
    session.execute("CREATE TABLE IF NOT EXISTS simplex.songs (" + "id int PRIMARY KEY," + "title text,"
            + "album text," + "artist text," + "tags set<text>," + "data blob," + ");");
    session.execute("CREATE INDEX IF NOT EXISTS album_idx ON simplex.songs(album);");
    session.execute("CREATE INDEX IF NOT EXISTS title_idx ON simplex.songs(title);");
    PreparedStatement statement = session.prepare(
            "INSERT INTO simplex.songs " + "(id, title, album, artist, tags) " + "VALUES (?, ?, ?, ?, ?);");
    BoundStatement boundStatement = new BoundStatement(statement);
    List<Song> songList = new ArrayList<Song>();
    prepareStartingData(songList);
    Iterator it = songList.iterator();
    while (it.hasNext()) {
        Song song = (Song) it.next();
        ResultSet res = session.execute(boundStatement.bind(song.getId(), song.getTitle(), song.getAlbum(),
                song.getArtist(), song.getTags()));
    }
    session.close();
    cluster.close();
    try {
        Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:example.springdata.cassandra.people.ReactivePersonRepositoryIntegrationTest.java

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 *///from  w  w w.java 2  s  . c om
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    repository.count() //
            .doOnNext(System.out::println) //
            .thenMany(repository.saveAll(Flux.just(new Person("Hank", "Schrader", 43), //
                    new Person("Mike", "Ehrmantraut", 62)))) //
            .last() //
            .flatMap(v -> repository.count()) //
            .doOnNext(System.out::println) //
            .doOnTerminate(countDownLatch::countDown) //
            .subscribe();

    countDownLatch.await();
}

From source file:com.mobius.software.mqtt.performance.runner.ScenarioRunner.java

public void start() throws InterruptedException {
    List<RequestWorker> workers = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(requests.size());
    for (ScenarioRequest request : requests)
        workers.add(new RequestWorker(request, latch));

    ExecutorService service = Executors.newFixedThreadPool(workers.size());
    for (RequestWorker worker : workers)
        service.submit(worker);//from   w ww.  ja  v a  2  s  .  com
    latch.await();

    service.shutdownNow();
}

From source file:org.housecream.restmcu.it.resource.LatchBoardResource.java

public void resetLatch() {
    setLatch = new CountDownLatch(1);
}

From source file:com.baidu.oped.apm.profiler.errorTest.ConcurrentCall.java

@Test
public void test() throws IOException, InterruptedException {
    ((ThreadPoolExecutor) executorService).prestartAllCoreThreads();

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    cm.setMaxTotal(200);//from  w  w  w .jav  a 2  s.  c o m
    cm.setDefaultMaxPerRoute(200);

    final HttpClient client = new DefaultHttpClient(cm);
    int call = 400;
    final CountDownLatch latch = new CountDownLatch(call);
    for (int i = 0; i < call; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = getUrl();
                    logger.info("execute {}", url);
                    final HttpGet httpGet = new HttpGet(url);
                    final HttpResponse execute = client.execute(httpGet);
                    execute.getEntity().getContent().close();

                } catch (ClientProtocolException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                } catch (IOException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                } finally {
                    latch.countDown();
                }
            }
        });
    }
    latch.await();
    executorService.shutdown();
    cm.shutdown();

}

From source file:com.netflix.curator.x.discovery.TestServiceCache.java

@Test
public void testInitialLoad() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);/*w w w  .j  a v a2s. c o m*/
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class)
                .basePath("/discovery").client(client).build();
        closeables.add(discovery);
        discovery.start();

        ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache);

        final CountDownLatch latch = new CountDownLatch(3);
        ServiceCacheListener listener = new ServiceCacheListener() {
            @Override
            public void cacheChanged() {
                latch.countDown();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        cache.addListener(listener);
        cache.start();

        ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10064).build();
        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10065).build();
        ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10066).build();
        discovery.registerService(instance1);
        discovery.registerService(instance2);
        discovery.registerService(instance3);

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        ServiceCache<String> cache2 = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache2);
        cache2.start();

        Assert.assertEquals(cache2.getInstances().size(), 3);
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderLatch.java

@Test
public void testResetRace() throws Exception {
    Timing timing = new Timing();
    LeaderLatch latch = null;/*w  w  w  .j a v  a  2 s. co m*/
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        latch = new LeaderLatch(client, PATH_NAME);

        latch.debugResetWaitLatch = new CountDownLatch(1);
        latch.start(); // will call reset()
        latch.reset(); // should not result in two nodes

        timing.sleepABit();

        latch.debugResetWaitLatch.countDown();

        timing.sleepABit();

        Assert.assertEquals(client.getChildren().forPath(PATH_NAME).size(), 1);
    } finally {
        IOUtils.closeQuietly(latch);
        IOUtils.closeQuietly(client);
    }
}

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

@Test
public void testGetVmAsync() throws IOException, InterruptedException {
    final SystemStatus systemStatus = new SystemStatus();
    systemStatus.setStatus(StatusType.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(systemStatus);

    setupMocks(serialized, HttpStatus.SC_OK);

    SystemStatusApi systemStatusApi = new SystemStatusApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    systemStatusApi.getSystemStatusAsync(new FutureCallback<SystemStatus>() {
        @Override/*from  w  w  w.  j  a  v  a 2 s .  c  o m*/
        public void onSuccess(@Nullable SystemStatus result) {
            assertEquals(result, systemStatus);
            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.nsxclient.apis.FabricApiTest.java

@Test
public void testRegisterFabricNode() throws IOException, InterruptedException {
    final FabricNode mockResponse = new FabricNode();
    mockResponse.setId("id");
    mockResponse.setExternalId("externalId");
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_CREATED);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.registerFabricNode(new FabricNodeCreateSpec(),
            new com.google.common.util.concurrent.FutureCallback<FabricNode>() {
                @Override//from w  w w  .  j  a va 2 s.c  o m
                public void onSuccess(FabricNode result) {
                    assertEquals(result, mockResponse);
                    latch.countDown();
                }

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

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