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.kurento.kmf.test.base.GridBrowserMediaApiTest.java

private void startNodes() throws InterruptedException {
    countDownLatch = new CountDownLatch(nodes.size());

    for (final Node n : nodes) {
        Thread t = new Thread() {
            public void run() {
                try {
                    startNode(n);//from   w  w  w . j  av  a2s. com
                } catch (IOException e) {
                    log.error("Exception starting node {} : {}", n.getAddress(), e.getClass());
                }
            }
        };
        t.start();
    }

    if (!countDownLatch.await(TIMEOUT_NODE, TimeUnit.SECONDS)) {
        Assert.fail("Timeout waiting nodes (" + TIMEOUT_NODE + " seconds)");
    }
}

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

@Test
public void testBasic() throws Exception {
    final int SELECTOR_QTY = 10;

    List<LeaderSelector> selectors = Lists.newArrayList();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {// w w w.ja v a 2s  .  c  o  m
        client.start();

        final CountDownLatch leaderLatch = new CountDownLatch(1);
        final CountDownLatch workingLatch = new CountDownLatch(SELECTOR_QTY);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                leaderLatch.countDown();
                Thread.currentThread().join();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };

        for (int i = 0; i < SELECTOR_QTY; ++i) {
            LeaderSelector selector = new LeaderSelector(client, "/ls", listener) {
                @Override
                void doWork() throws Exception {
                    workingLatch.countDown();
                    super.doWork();
                }
            };
            selector.setId(Integer.toString(i));
            selectors.add(selector);
        }

        for (LeaderSelector selector : selectors) {
            selector.start();
        }

        Assert.assertTrue(leaderLatch.await(10, TimeUnit.SECONDS));
        Assert.assertTrue(workingLatch.await(10, TimeUnit.SECONDS));

        Thread.sleep(1000); // some time for locks to acquire

        Collection<Participant> participants = selectors.get(0).getParticipants();
        for (int i = 1; i < selectors.size(); ++i) {
            Assert.assertEquals(participants, selectors.get(i).getParticipants());
        }

        Set<String> ids = Sets.newHashSet();
        int leaderCount = 0;
        for (Participant participant : participants) {
            if (participant.isLeader()) {
                ++leaderCount;
            }
            Assert.assertFalse(ids.contains(participant.getId()));
            ids.add(participant.getId());
        }
        Assert.assertEquals(leaderCount, 1);

        Set<String> expectedIds = Sets.newHashSet();
        for (int i = 0; i < SELECTOR_QTY; ++i) {
            expectedIds.add(Integer.toString(i));
        }
        Assert.assertEquals(expectedIds, ids);
    } finally {
        for (LeaderSelector selector : selectors) {
            IOUtils.closeQuietly(selector);
        }
        IOUtils.closeQuietly(client);
    }
}

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

@Test
public void testGetImageAsync() throws IOException, InterruptedException {
    final Image image = new Image();
    image.setId("image1");

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(image);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ImagesApi imagesApi = new ImagesRestApi(this.restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    imagesApi.getImageAsync(image.getId(), new FutureCallback<Image>() {
        @Override/*  ww w .  ja  v  a 2s.c  o m*/
        public void onSuccess(@Nullable Image result) {
            assertEquals(result, image);
            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: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();
                            }//from   w  w w .  j av  a 2 s  .c  o  m
                            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:com.uber.tchannel.ping.PingClient.java

public void run() throws Exception {
    TChannel tchannel = new TChannel.Builder("ping-client").build();
    SubChannel subChannel = tchannel.makeSubChannel("ping-server");
    final ConcurrentHashMap<String, Integer> msgs = new ConcurrentHashMap<String, Integer>();
    final CountDownLatch done = new CountDownLatch(requests);

    for (int i = 0; i < requests; i++) {
        JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
                .setBody(new Ping("{'key': 'ping?'}")).setHeader("some", "header").setTimeout(100 + i).build();
        TFuture<JsonResponse<Pong>> f = subChannel.send(request, InetAddress.getByName(host), port);

        f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
            @Override//from  ww w  . j  a  va  2  s . c  o m
            public void onResponse(JsonResponse<Pong> pongResponse) {
                done.countDown();
                String msg = pongResponse.toString();
                if (msgs.containsKey(msg)) {
                    msgs.put(msg, msgs.get(msg) + 1);
                } else {
                    msgs.put(msg, 1);
                }
            }
        });
    }

    done.await();
    for (String msg : msgs.keySet()) {
        System.out.println(String.format("%s\n\tcount:%d", msg, msgs.get(msg)));
    }

    tchannel.shutdown(false);
}

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case3.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);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from ww w . ja  v  a 2s . c  om

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT 1 FROM DUAL");
                        rs.next();
                        // Assert.isTrue(!rs.isClosed());
                        rs.close();
                        // Assert.isTrue(!stmt.isClosed());
                        stmt.close();
                        Assert.isTrue(stmt.isClosed());
                        conn.close();
                    }
                } 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);
}

From source file:io.fabric8.msg.jnatsd.JNatsd.java

@PostConstruct
public void start() {
    if (started.compareAndSet(false, true)) {
        try {//from  ww  w . j a  v  a 2  s  . c o m
            serverInfo.setHost("0.0.0.0");
            serverInfo.setPort(getConfiguration().getClientPort());
            serverInfo.setVersion("1.0");
            serverInfo.setMaxPayload(getConfiguration().getMaxPayLoad());

            int numberOfServers = getConfiguration().getNumberOfNetServers();
            if (numberOfServers <= 0) {
                numberOfServers = Runtime.getRuntime().availableProcessors();
            }

            final CountDownLatch countDownLatch = new CountDownLatch(numberOfServers);

            VertxOptions vertxOptions = new VertxOptions();

            System.setProperty("vertx.disableFileCPResolving", "true");
            vertx = Vertx.vertx(vertxOptions);

            LOG.info("Creating " + numberOfServers + " vert.x servers for JNatsd");
            for (int i = 0; i < numberOfServers; i++) {

                NetServer server = vertx.createNetServer();
                server.connectHandler(socket -> {
                    JNatsSocketClient natsClient = new JNatsSocketClient(this, serverInfo, socket);
                    natsClient.start();
                    addClient(natsClient);
                });

                server.listen(getConfiguration().getClientPort(), event -> {
                    if (event.succeeded()) {
                        actualPort = event.result().actualPort();
                        countDownLatch.countDown();
                    }
                });

                servers.add(server);
            }

            if (countDownLatch.await(5, TimeUnit.SECONDS)) {
                pingPong.start();
                serverInfo.setPort(actualPort);
                LOG.info("JNatsd initialized (" + numberOfServers + " servers:port=" + actualPort
                        + ") and running ...");
            } else {
                LOG.error("Failed to initialize JNatsd - could not bind to port");
                stop();
            }

        } catch (Throwable e) {
            LOG.error("Failed to initialize JNatsd", e);
        }
    }
}

From source file:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Test//from  w w w  .java2 s .  c o  m
public void testMulti() throws Exception {
    final String PATH = "/queue";
    final int CLIENT_QTY = 4;
    final int MAX_ITEMS = 10;
    final int ADD_ITEMS = MAX_ITEMS * 100;
    final int SLOP_FACTOR = 2;

    final QueueConsumer<String> consumer = new QueueConsumer<String>() {
        @Override
        public void consumeMessage(String message) throws Exception {
            Thread.sleep(10);
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    };

    final Timing timing = new Timing();
    final ExecutorService executor = Executors.newCachedThreadPool();
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executor);

    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        client.create().forPath(PATH);

        final CountDownLatch isWaitingLatch = new CountDownLatch(1);
        final AtomicBoolean isDone = new AtomicBoolean(false);
        final List<Integer> counts = new CopyOnWriteArrayList<Integer>();
        final Object lock = new Object();
        executor.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                Watcher watcher = new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        synchronized (lock) {
                            lock.notifyAll();
                        }
                    }
                };

                while (!Thread.currentThread().isInterrupted() && client.isStarted() && !isDone.get()) {
                    synchronized (lock) {
                        int size = client.getChildren().usingWatcher(watcher).forPath(PATH).size();
                        counts.add(size);
                        isWaitingLatch.countDown();
                        lock.wait();
                    }
                }
                return null;
            }
        });
        isWaitingLatch.await();

        for (int i = 0; i < CLIENT_QTY; ++i) {
            final int index = i;
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = null;
                    DistributedQueue<String> queue = null;

                    try {
                        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
                                timing.connection(), new RetryOneTime(1));
                        client.start();
                        queue = QueueBuilder.builder(client, consumer, serializer, PATH).executor(executor)
                                .maxItems(MAX_ITEMS).putInBackground(false).lockPath("/locks").buildQueue();
                        queue.start();

                        for (int i = 0; i < ADD_ITEMS; ++i) {
                            queue.put("" + index + "-" + i);
                        }
                    } finally {
                        IOUtils.closeQuietly(queue);
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.take().get();
        }

        isDone.set(true);
        synchronized (lock) {
            lock.notifyAll();
        }

        for (int count : counts) {
            Assert.assertTrue(counts.toString(), count <= (MAX_ITEMS * SLOP_FACTOR));
        }
    } finally {
        executor.shutdownNow();
        IOUtils.closeQuietly(client);
    }
}

From source file:com.ragstorooks.testrr.Runner.java

/**
 * To be invoked when all the parameters have been configured, to generate the load on the system under test.
 *///from  w ww  . j a v  a2 s .c  om
public void run() {
    log.info(String.format("RPRunner(numberOfRuns=%d, numberOfConcurrentStarts=%d)", numberOfRuns,
            numberOfConcurrentStarts));

    if (useDeterministicNumberOfRuns) {
        scenariosList = new ArrayList<ScenarioBase>();
        for (ScenarioBase scenario : scenarioWeightings.keySet()) {
            scenariosList.add(scenario);
        }
    }

    allScenariosCompleteLatch = new CountDownLatch(numberOfRuns);
    normalizeWeightings();

    long startTime = System.currentTimeMillis();

    if (synchronizedScheduling)
        runWithSynchronizedScheduling();
    else
        runWithAdHocScheduling();

    waitForCoolDownPeriod();

    totalRunTimeMilliSeconds = System.currentTimeMillis() - startTime;

}

From source file:io.galeb.services.healthchecker.testers.ApacheHttpClientTester.java

public boolean connect() throws RuntimeException, InterruptedException, ExecutionException {
    if (url == null || returnType == null || expectedReturn == null) {
        return false;
    }//from ww  w .ja  v a2 s.  c om
    final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        final CountDownLatch latch = new CountDownLatch(1);
        final HttpGet request = new HttpGet(url);
        request.setHeader(HttpHeaders.HOST, host);
        final HttpAsyncRequestProducer producer = HttpAsyncMethods.create(request);
        final RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
                .setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout)
                .setConnectionRequestTimeout(defaultTimeout).build();
        request.setConfig(requestConfig);
        final AsyncCharConsumer<HttpResponse> consumer = new AsyncCharConsumer<HttpResponse>() {

            HttpResponse response;

            @Override
            protected void onCharReceived(CharBuffer buf, IOControl iocontrol) throws IOException {
                return;
            }

            @Override
            protected HttpResponse buildResult(HttpContext context) throws Exception {
                return response;
            }

            @Override
            protected void onResponseReceived(HttpResponse response) throws HttpException, IOException {
                this.response = response;
            }

        };
        httpclient.execute(producer, consumer, new FutureCallback<HttpResponse>() {

            @Override
            public void cancelled() {
                latch.countDown();
                isOk = false;
            }

            @Override
            public void completed(HttpResponse response) {
                latch.countDown();

                final int statusCode = response.getStatusLine().getStatusCode();
                InputStream contentIS = null;
                String content = "";
                try {
                    contentIS = response.getEntity().getContent();
                    content = IOUtils.toString(contentIS);

                } catch (IllegalStateException | IOException e) {
                    logger.ifPresent(log -> log.debug(e));
                }

                if (returnType.startsWith("httpCode")) {
                    returnType = returnType.replaceFirst("httpCode", "");
                }
                // isOk = statusCode == Integer.parseInt(returnType); // Disable temporarily statusCode check
                isOk = true;
            }

            @Override
            public void failed(Exception e) {
                latch.countDown();
                isOk = false;
                logger.ifPresent(log -> log.debug(e));
            }

        });
        latch.await();

    } catch (final RuntimeException e) {
        isOk = false;
        logger.ifPresent(log -> log.error(e));
    } finally {
        try {
            httpclient.close();
        } catch (final IOException e) {
            logger.ifPresent(log -> log.debug(e));
        }
    }
    return isOk;
}