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.cloudant.sync.datastore.ForceInsertTest.java

@Test
public void notification_forceinsert() {
    documentUpdated = new CountDownLatch(1);
    documentCreated = new CountDownLatch(2); // 2 because the call to createDocument will also fire
    // create a document and insert the first revision
    BasicDocumentRevision doc1_rev1 = datastore.createDocument(bodyOne);

    ArrayList<String> revisionHistory = new ArrayList<String>();
    revisionHistory.add(doc1_rev1.getRevision());

    // now do a force insert - we should get an updated event as it's already there
    datastore.forceInsert(doc1_rev1, revisionHistory, null, false);
    boolean ok1 = NotificationTestUtils.waitForSignal(documentUpdated);
    Assert.assertTrue("Didn't receive document updated event", ok1);

    // now do a force insert but with a different id - we should get a (2nd) created event
    doc1_rev1.setId("new-id-12345");
    datastore.forceInsert(doc1_rev1, revisionHistory, null, false);
    boolean ok2 = NotificationTestUtils.waitForSignal(documentCreated);
    Assert.assertTrue("Didn't receive document created event", ok2);
}

From source file:de.taimos.httputils.Tester1.java

/**
 * /*from   w ww .j  a v a2s. c o m*/
 */
@Test
public void testGetAsync() throws InterruptedException {
    final CountDownLatch cdl = new CountDownLatch(1);
    WS.url("http://www.heise.de").getAsync(new HTTPResponseCallback() {

        @Override
        public void response(HttpResponse response) {
            Assert.assertEquals(WS.getStatus(response), 200);
            Assert.assertTrue(WS.isStatusOK(response));
            final String body = WS.getResponseAsString(response);
            Assert.assertNotNull(body);
            Assert.assertFalse(body.isEmpty());
            cdl.countDown();
        }

        @Override
        public void fail(Exception e) {
            System.out.println(e);
        }
    });
    Assert.assertTrue(cdl.await(10, TimeUnit.SECONDS));
}

From source file:com.dianping.apistatic.Job.MovieShowDetailCrawlerJob.java

@Override
protected void execute() throws Exception {
    List<Integer> movieShowIds = readIntListFromFile(Constants.MOVIESHOWIDS_PATH);
    if (CollectionUtils.isEmpty(movieShowIds)) {
        log("movieShowIds?", new RuntimeException("movieShowIds "));
        return;/*from  w  w w  . j  a  v  a2s .  com*/
    }

    int partitionSize = (movieShowIds.size() > 5 ? movieShowIds.size() / 5 : movieShowIds.size());
    List<List<Integer>> movieShowIdsList = Lists.partition(movieShowIds, partitionSize);
    CountDownLatch countDownLatch = new CountDownLatch(movieShowIdsList.size());

    for (List<Integer> list : movieShowIdsList) {
        MovieShowCrawlerThread thread = new MovieShowCrawlerThread(list, countDownLatch);
        thread.start();
    }
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log("CountDownLatch InterruptedException", e);
    }
}

From source file:test.config.WebAppInitializer.java

private void setupDispatchScenario(ServletContext servletContext) {

    CountDownLatch latch = new CountDownLatch(1);

    Dynamic servlet;/*from   w  w w  .  ja  v a2s  . c om*/
    servlet = servletContext.addServlet("DispA", new ForwardingServlet("A", "/dispScenarioB/b?b=B", latch));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/dispScenarioA/*");

    servlet = servletContext.addServlet("DispB", new ForwardingServlet("B", "/dispScenarioC/c?c=C", null));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/dispScenarioB/*");

    servlet = servletContext.addServlet("DispC",
            new DispatchingAsyncServlet("C", "/dispScenarioD/d?d=D", latch));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/dispScenarioC/*");

    servlet = servletContext.addServlet("DispD", new ForwardingServlet("D", "/WEB-INF/page.jsp", null));
    servlet.setAsyncSupported(true);
    servlet.addMapping("/dispScenarioD/*");
}

From source file:com.liferay.mobile.android.async.GroupServiceAsyncTest.java

@Test
public void getUserSites() throws Exception {
    Session session = new SessionImpl(this.session);

    final JSONArray[] sites = { null };
    final CountDownLatch lock = new CountDownLatch(1);

    session.setCallback(new JSONArrayCallback() {

        @Override//from   www.  jav a 2  s.c o m
        public void onSuccess(JSONArray result) {
            try {
                sites[0] = result;
                lock.countDown();
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    GroupService service = new GroupService(session);
    service.getUserSitesGroups();

    lock.await(500, TimeUnit.MILLISECONDS);
    GroupServiceTest.assertUserSites(sites[0]);
}

From source file:org.doxu.g2.gwc.crawler.Crawler.java

public Crawler() {
    session = new CrawlSession();
    crawlCompletedBarrier = new CountDownLatch(1);
}

From source file:ch.cyberduck.core.io.ThreadedStreamCloser.java

@Override
public void close(final InputStream in) throws ConnectionTimeoutException {
    final CountDownLatch signal = new CountDownLatch(1);
    threadFactory.newThread(new Runnable() {
        @Override/*from ww w .j a  v a 2 s  . c  om*/
        public void run() {
            IOUtils.closeQuietly(in);
            signal.countDown();
        }
    }).start();
    try {
        if (!signal.await(preferences.getInteger("connection.timeout.seconds"), TimeUnit.SECONDS)) {
            throw new StreamCloseTimeoutException("Timeout closing input stream", null);
        }
    } catch (InterruptedException e) {
        throw new ConnectionTimeoutException(e.getMessage(), e);
    }
}

From source file:com.fusesource.forge.jmstest.tests.simple.SimpleConsumer.java

protected void run() {
    Connection con = null;/*w w w.ja  v a  2 s .c  o m*/
    Session session = null;
    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);
    try {
        con = getConnection();
        session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dest = getDestinationProvider().getDestination(session, "queue:TEST");
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                String grp = null;
                long nr = 0L;
                try {
                    grp = msg.getStringProperty("JMSXGroupID");
                    nr = msg.getLongProperty("MsgNr");
                } catch (JMSException jme) {
                }
                log().info("Received Message Group=(" + grp + ") MsgNr=" + nr);
                latch.countDown();
            }
        });
        con.start();
        latch.await();
        con.close();
    } catch (Exception e) {
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.bpmscript.integration.spring.SpringIntegrationTest.java

public void testSpringIntegration() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    MessageBus messageBus = new MessageBus();
    QueueChannel oneChannel = new QueueChannel(10);
    QueueChannel twoChannel = new QueueChannel(10);
    messageBus.registerChannel("onechannel", oneChannel);
    messageBus.registerChannel("twochannel", twoChannel);
    messageBus.registerHandler("onehandler", new MessageHandler() {

        public Message<?> handle(Message<?> message) {
            log.info(message.getPayload());
            latch.countDown();/*  w  w w.j  a  v  a2s .c om*/
            return new StringMessage("Hi...");
        }

    }, new Subscription(oneChannel));
    messageBus.registerHandler("twohandler", new MessageHandler() {

        public Message<?> handle(Message<?> message) {
            log.info(message.getPayload());
            latch.countDown();
            return null;
        }

    }, new Subscription(twoChannel));
    messageBus.start();
    StringMessage stringMessage = new StringMessage("Hello World!");
    stringMessage.getHeader().setReturnAddress("twochannel");
    oneChannel.send(stringMessage);
    assertTrue(latch.await(2, TimeUnit.SECONDS));
    messageBus.stop();
}

From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedLockTest.java

@Test
protected void test_lock() {
    ExecutorService exeucotr = Executors.newCachedThreadPool();
    final int count = 50;
    final CountDownLatch latch = new CountDownLatch(count);
    final DistributedLock[] nodes = new DistributedLock[count];
    for (int i = 0; i < count; i++) {
        final DistributedLock node = new DistributedLock(dir);
        nodes[i] = node;//from   w  w  w  .j  a  va  2s. c o  m
        exeucotr.submit(new Runnable() {

            public void run() {
                try {
                    node.lock();
                    Thread.sleep(100 + RandomUtils.nextInt(100));
                    System.out.println("id: " + node.getId() + " is leader: " + node.isOwner());
                } catch (InterruptedException e) {
                    want.fail();
                } catch (KeeperException e) {
                    want.fail();
                } finally {
                    latch.countDown();
                    try {
                        node.unlock();
                    } catch (KeeperException e) {
                        want.fail();
                    }
                }

            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        want.fail();
    }

    exeucotr.shutdown();
}