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.subgraph.vega.internal.crawler.WebCrawler.java

@Override
public synchronized void start() {
    if (crawlerRunning)
        throw new IllegalStateException("Cannot call start() on running crawler instance");

    latch = new CountDownLatch(requestThreadCount + responseThreadCount);

    updateProgress();/*from ww  w . jav a 2 s.  c  o  m*/

    for (int i = 0; i < responseThreadCount; i++) {
        HttpResponseProcessor responseProcessor = new HttpResponseProcessor(this, requestQueue, responseQueue,
                latch, counter, outstandingTasks);
        responseProcessors.add(responseProcessor);
        executor.execute(responseProcessor);
    }

    for (int i = 0; i < requestThreadCount; i++) {
        RequestConsumer consumer = new RequestConsumer(requestEngine, requestQueue, responseQueue, latch);
        requestConsumers.add(consumer);
        executor.execute(consumer);
    }
    crawlerRunning = true;
}

From source file:com.microsoft.office.integration.test.FoldersAsyncTestCase.java

public void testUpdate() {
    prepareFolder();//from   w w  w  .j  a v  a2 s.  c o  m
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                updateAndCheck();
                removeFolder();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });

    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testUpdate() timed out");
        }
    } catch (InterruptedException e) {
        fail("testUpdate() has been interrupted");
    }
}

From source file:ninja.eivind.hotsreplayuploader.ClientTest.java

@Test
public void testJavaFXIsAvailable() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(2);
    Task<Void> javaFxTask = new Task<Void>() {
        @Override//  ww  w.  jav  a2s .c  om
        protected Void call() throws Exception {
            latch.countDown();
            return null;
        }
    };
    javaFxTask.setOnSucceeded((result) -> latch.countDown());
    new Thread(javaFxTask).run();

    if (!latch.await(1, TimeUnit.SECONDS)) {
        fail("JavaFX is not available.");
    }
}

From source file:com.fusesource.forge.jmstest.threading.LimitedTimeScheduledExecutor.java

public void waitUntilFinished() {
    synchronized (lock) {
        if (!isRunning) {
            return;
        }//w  ww . j  a v  a 2 s  . c o  m
    }
    CountDownLatch latch = new CountDownLatch(1);
    synchronized (waiting) {
        waiting.add(latch);
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
    }
}

From source file:com.nesscomputing.service.discovery.client.internal.ServiceDiscoveryReader.java

@Override
void visit(final List<String> childNodes, final ZooKeeper zookeeper, final long tick)
        throws InterruptedException {
    final Map<String, List<ServiceInformation>> serviceMap = new HashMap<String, List<ServiceInformation>>();

    if (!childNodes.isEmpty()) {
        final List<ServiceInformation> rawServices = new ArrayList<ServiceInformation>(childNodes.size());
        final CountDownLatch latch = new CountDownLatch(childNodes.size());

        final long now = System.nanoTime();

        for (final String child : childNodes) {

            final String childPath = getNodePath(child);

            if (badNodes.containsKey(childPath)) {
                final Long penaltyEndsTime = badNodes.get(childPath);
                if (penaltyEndsTime != null && penaltyEndsTime > now) {
                    // Decrement the countdown latch, because there will be no callback for this
                    // node.
                    latch.countDown();/*ww  w  .  j av a2  s .c  o  m*/
                    // Ignore a bad node for a while.
                    continue;
                }
                LOG.info("Unmarking %s as a bad node!", childPath);
                badNodes.remove(childPath);
            }

            zookeeper.getData(childPath, false, new DataCallback() {
                @Override
                public void processResult(final int rc, final String path, final Object ctx, final byte[] data,
                        final Stat stat) {

                    ServiceInformation si = null;
                    try {
                        if (data != null && data.length > 0) {
                            si = objectMapper.readValue(data, ServiceInformation.class);
                            LOG.trace("%s contains %s", path, si);
                        } else {
                            // This can sometimes happen if a node that we want to inspect
                            // disappears between callback post and callback processing.
                            LOG.trace("Got callback but no data!");
                        }

                    } catch (IOException ioe) {
                        LOG.debug(ioe, "While deserializing %s", new String(data, Charsets.UTF_8));
                        LOG.info("Marking %s as a bad node!", path);
                        // Put a bad node into the penalty box.
                        badNodes.put(path, now + penaltyTime);
                    } finally {
                        synchronized (rawServices) {
                            if (si != null) {
                                rawServices.add(si);
                            }
                        }
                        latch.countDown();
                    }
                }
            }, null);
        }

        if (!latch.await(discoveryConfig.getZookeeperTimeout().getMillis(), TimeUnit.MILLISECONDS)) {
            LOG.warn("Timeout waiting for callbacks, some nodes were not parsed.");
        }

        // Make sure that even with late callbacks, this will not throw spurious ConcurrentModificationExceptions
        synchronized (rawServices) {
            for (final ServiceInformation si : rawServices) {
                List<ServiceInformation> services = serviceMap.get(si.getServiceName());
                if (services == null) {
                    services = new ArrayList<ServiceInformation>();
                    serviceMap.put(si.getServiceName(), services);
                }
                services.add(si);
            }
        }
    }

    Map<String, ConsistentRingGroup> serviceGroups = Maps.newHashMap();
    for (Map.Entry<String, List<ServiceInformation>> entry : serviceMap.entrySet()) {
        ConsistentRingGroup currentGroup = stateHolder.getState().get(entry.getKey());
        //Rebuilding a group is kind of expensive, so reuse the old group if it hasn't changed
        if (currentGroup != null
                && Sets.newHashSet(entry.getValue()).equals(Sets.newHashSet(currentGroup.getAll()))) {
            serviceGroups.put(entry.getKey(), currentGroup);
        } else {
            serviceGroups.put(entry.getKey(), new ConsistentRingGroup(entry.getValue()));
        }
    }
    stateHolder.setState(serviceGroups);
}

From source file:se.vgregion.pubsub.loadtesting.LoadtestingServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // ping publish
    // wait for notification
    // response/*from  w w  w . j a  va 2  s. c  o m*/
    // error if timeout

    if (req.getPathInfo().equals("/feed")) {
        // serve ATOM feed
        resp.getWriter().write(atom(getFragment(req)));
    } else {
        // publish

        UUID id = UUID.randomUUID();
        String publicationUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/feed#" + id;

        String hubUrl = System.getProperty("hub.url");
        if (hubUrl == null) {
            throw new RuntimeException("System properti hub.url missing");
        }

        try {
            CountDownLatch latch = new CountDownLatch(1);
            publications.put(id, latch);

            HttpPost publication = new HttpPost(hubUrl);
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("hub.mode", "publish"));
            parameters.add(new BasicNameValuePair("hub.url", publicationUrl));

            publication.setEntity(new UrlEncodedFormEntity(parameters));

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse publicationResponse = httpClient.execute(publication);

            if (publicationResponse.getStatusLine().getStatusCode() == 204) {
                try {
                    if (latch.await(20000, TimeUnit.MILLISECONDS)) {
                        // all happy, return
                        return;
                    } else {
                        // timeout
                        resp.sendError(591);
                    }
                } catch (InterruptedException e) {
                    // interrupted
                    resp.sendError(592);
                }
            } else {
                // publication failed
                resp.sendError(publicationResponse.getStatusLine().getStatusCode(),
                        publicationResponse.getStatusLine().getReasonPhrase());
            }
        } finally {
            // try to prevent memory leaks
            publications.remove(id);
        }
    }
}

From source file:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java

@Test
public void testReleaseInterrupted() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    SteppableThread latchStepper = new SteppableWaitForLatch(latch);

    interruptInWait(latchStepper, TestMode.RELEASE);

    ((CyclicBarrier) ReflectionTestUtils.getField(latchStepper, "stepStart")).reset();
    latchStepper.start();/*  www.  j av a  2s . c  o  m*/
    latch.countDown();
    latchStepper.releaseAndJoin();
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkJMSProducerWrapper.java

public void start() {
    synchronized (started) {
        if (!started) {
            log().info("ProducerWrapper (" + getClientId() + ") starting.");
            super.start();
            CountingProbe cp = new CountingProbe(getClientId() + "-COUNTER");
            cp.addObserver(getSamplePersistenceAdapter());
            setProbe(cp);/*  w  ww.j a  va2s. c o  m*/
            getProbeRunner().addProbe(cp);
            benchmarkIterationLatch = new CountDownLatch(1);
            new Thread(this, getClientId().toString()).start();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        benchmarkIterationLatch.await();
                        log().info("ProducerWrapper (" + getClientId() + ") completed.");
                    } catch (InterruptedException e) {
                        log().warn("Benchmark (" + getClientId() + ") interrupted.");
                    }
                }
            }).start();
        }
    }
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Test
public void testSetCallbackIsAppliedProperly() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    tempWatcher.setCallback(file -> latch.countDown());
    TempWatcher lastChild = getChildRecursively(tempWatcher);
    Consumer<File> callback = lastChild.getCallback();

    callback.accept(null);/*from   w  w w  .  j a v a2  s  .co m*/

    if (!latch.await(500, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException("Latch was not tripped.");
    }
}

From source file:com.alibaba.dubbo.demo.consumer.DemoAction.java

public void start() throws Exception {
    int threads = 100;

    final DescriptiveStatistics stats = new SynchronizedDescriptiveStatistics();

    DubboBenchmark.BenchmarkMessage msg = prepareArgs();
    final byte[] msgBytes = msg.toByteArray();

    int n = 1000000;
    final CountDownLatch latch = new CountDownLatch(n);

    ExecutorService es = Executors.newFixedThreadPool(threads);

    final AtomicInteger trans = new AtomicInteger(0);
    final AtomicInteger transOK = new AtomicInteger(0);

    long start = System.currentTimeMillis();
    for (int i = 0; i < n; i++) {
        es.submit(() -> {/*from ww w .  ja  v  a  2 s.  co m*/
            try {

                long t = System.currentTimeMillis();
                DubboBenchmark.BenchmarkMessage m = testSay(msgBytes);
                t = System.currentTimeMillis() - t;
                stats.addValue(t);

                trans.incrementAndGet();

                if (m != null && m.getField1().equals("OK")) {
                    transOK.incrementAndGet();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        });
    }

    latch.await();

    start = System.currentTimeMillis() - start;

    System.out.printf("sent     requests    : %d\n", n);
    System.out.printf("received requests    : %d\n", trans.get());
    System.out.printf("received requests_OK : %d\n", transOK.get());
    System.out.printf("throughput  (TPS)    : %d\n", n * 1000 / start);

    System.out.printf("mean: %f\n", stats.getMean());
    System.out.printf("median: %f\n", stats.getPercentile(50));
    System.out.printf("max: %f\n", stats.getMax());
    System.out.printf("min: %f\n", stats.getMin());

    System.out.printf("99P: %f\n", stats.getPercentile(90));
}