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:fr.keemto.scheduling.ScheduledTaskIT.java

@Test
public void shouldExecuteFetcherAsychronouslyWithDelay() throws Exception {

    CountDownLatch latch = new CountDownLatch(10);
    Task countDownTask = new CountDownTask(latch);

    scheduler.scheduleTask(countDownTask);
    latch.await(2000, TimeUnit.MILLISECONDS);

    assertThat(latch.getCount(), equalTo((long) 0));
}

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

@Test
protected void test_lock() {
    ExecutorService exeucotr = Executors.newCachedThreadPool();
    final int count = 50;
    final CountDownLatch latch = new CountDownLatch(count);

    final DistributedReentrantLock lock = new DistributedReentrantLock(dir);
    for (int i = 0; i < count; i++) {
        exeucotr.submit(new Runnable() {

            public void run() {
                try {
                    Thread.sleep(1000);
                    lock.lock();//from w  w  w . j  a v a2s  . com
                    Thread.sleep(100 + RandomUtils.nextInt(100));

                    System.out.println("id: " + lock.getId() + " is leader: " + lock.isOwner());
                } catch (InterruptedException e) {
                    want.fail();
                } catch (KeeperException e) {
                    want.fail();
                } finally {
                    latch.countDown();
                    try {
                        lock.unlock();
                    } catch (KeeperException e) {
                        want.fail();
                    }
                }

            }
        });
    }

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

    exeucotr.shutdown();
}

From source file:org.kurento.tutorial.helloworld.HelloWorldController.java

@RequestMapping(value = "/helloworld", method = RequestMethod.POST)
private String processRequest(@RequestBody String sdpOffer) {

    final CountDownLatch eventReceived = new CountDownLatch(1);
    // Media Logic
    MediaPipeline pipeline = kurento.createMediaPipeline();
    WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
    webRtcEndpoint.addOnIceGatheringDoneListener(new EventListener<OnIceGatheringDoneEvent>() {
        @Override//from  ww  w. j  a va  2 s . c om
        public void onEvent(OnIceGatheringDoneEvent event) {
            eventReceived.countDown();
        }
    });

    webRtcEndpoint.connect(webRtcEndpoint);
    webRtcEndpoint.processOffer(sdpOffer);
    webRtcEndpoint.gatherCandidates();

    try {
        eventReceived.await();
    } catch (InterruptedException e) {

    }
    // SDP negotiation (offer and answer)
    String responseSdp = webRtcEndpoint.getLocalSessionDescriptor();
    return responseSdp;
}

From source file:com.dianping.apistatic.Job.SeatingplanCrawlerJob.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  ww .  j  av a 2  s.co m*/
    }

    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) {
        SeatingPlanCrawlerThread thread = new SeatingPlanCrawlerThread(list, countDownLatch);
        thread.start();
    }
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log("CountDownLatch InterruptedException", e);
    }
}

From source file:net.javacrumbs.futureconverter.common.test.spring.SpringConvertedFutureTestHelper.java

@Override
public void waitForCalculationToFinish(ListenableFuture<String> convertedFuture) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    convertedFuture.addCallback(new ListenableFutureCallback<String>() {
        @Override/*from   w  w w  . j a v  a 2 s  .  c  om*/
        public void onSuccess(String result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    });
    latch.await(1, TimeUnit.SECONDS);
}

From source file:ufo.remote.calls.benchmark.server.vertx.VertxServiceImpl.java

@PostConstruct
public void init() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final VertxOptions options = new VertxOptions();
    final Config conf = new Config();
    Vertx.clusteredVertx(options.setClusterHost("localhost").setClusterPort(0).setClustered(true)
            .setClusterManager(new HazelcastClusterManager(conf)), ar -> {
                if (ar.failed()) {
                    logger.error("Error starting Vertx cluster", ar.cause());
                }//w w  w  .  java 2 s.  co m
                logger.info("Vertx cluster node started [{}]");
                vertx = ar.result();
                logger.info("Initialising vertx verticles...");
                vertx.deployVerticle(webServerVerticle);
                latch.countDown();
            });
    latch.await();
}

From source file:interactivespaces.master.server.services.internal.ros.MasterRosContext.java

public void startup() {
    log.error("Starting up master ROS context");

    final NodeConfiguration nodeConfiguration = rosEnvironment.getPublicNodeConfigurationWithNodeName();
    nodeConfiguration.setNodeName("interactivespaces/master");

    final CountDownLatch registrationLatch = new CountDownLatch(1);

    NodeListener listener = new NodeListener() {

        @Override/*from  ww w  .j  a  v a 2 s .c o  m*/
        public void onStart(ConnectedNode connectedNode) {
            setConnectedNode(connectedNode);
            registrationLatch.countDown();
        }

        @Override
        public void onShutdownComplete(Node node) {
            log.error(String.format("Got ROS node complete shutdown for Interactive Spaces master node %s",
                    node.getName()));
        }

        @Override
        public void onShutdown(Node node) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(Node node, Throwable throwable) {
            log.error(String.format("Got ROS node error for Interactive Spaces master node %s", node.getName()),
                    throwable);
        }
    };
    rosEnvironment.newNode(nodeConfiguration, Lists.newArrayList(listener));
}

From source file:org.smartfrog.services.anubis.SmokeTest.java

public void testInProcess() throws Exception {
    TestNodeCfg.nextMagic();/*from  ww  w .  j  a va 2s .  c  o  m*/
    String stateName = "Whip It";
    int maxSleep = 500;
    int messageCount = 10;
    ArrayList<Node> nodes = new ArrayList<Node>();
    CountDownLatch launchLatch = new CountDownLatch(configurations.length);
    CountDownLatch startLatch = new CountDownLatch(configurations.length);
    CountDownLatch endLatch = new CountDownLatch(configurations.length);
    for (Class<?> config : configurations) {
        nodes.add(getNode(config, stateName, messageCount, maxSleep, launchLatch, startLatch, endLatch,
                configurations.length));
    }
    boolean stabilized = launchLatch.await(120, TimeUnit.SECONDS);
    assertTrue("Partition did not stabilize", stabilized);
    System.out.println("Partition stabilized");
    for (Node node : nodes) {
        node.start();
    }
    boolean started = startLatch.await(60, TimeUnit.SECONDS);
    assertTrue("Not all nodes started", started);
    System.out.println("Partition started");
    boolean ended = endLatch.await(60, TimeUnit.SECONDS);
    assertTrue("Not all messages were received: " + findMissing(nodes), ended);
    for (Node node : nodes) {
        node.shutDown();
    }
    for (Node sender : nodes) {
        List<SendHistory> sent = sender.getSendHistory();
        assertEquals(messageCount, sent.size());
        for (Node receiver : nodes) {
            List<ValueHistory> received = receiver.getValueHistory(sender.getIdentity());
            assertNotNull("Received no history from " + sender.getIdentity(), received);
            int lastCounter = -1;
            boolean first = true;
            List<ValueHistory> filtered = new ArrayList<ValueHistory>();
            for (ValueHistory msg : received) {
                if (msg.value == null) {
                    continue;
                }
                filtered.add(msg);
                assertEquals(Action.NEW, msg.action);
                if (first) {
                    first = false;
                    lastCounter = (Integer) msg.value;
                } else {
                    int counter = (Integer) msg.value;
                    assertEquals(String.format("invalid msg received by %s : %s", receiver.getIdentity(), msg),
                            lastCounter + 1, counter);
                    lastCounter = counter;
                }
            }
            for (int i = 0; i < sent.size(); i++) {
                assertEquals(sent.get(i).value, filtered.get(i).value);
            }
        }
    }
}

From source file:com.googlecode.xmlzen.XmlSlicerTest.java

@Test
public void testXmlSlicerListConcurrency() throws Exception {
    final CountDownLatch latch = new CountDownLatch(SLICER_ITERATIONS);
    final XmlSlicerList xsl = new XmlSlicerList();
    xsl.add(XmlSlicer.cut("1"));
    xsl.add(XmlSlicer.cut("2"));
    xsl.add(XmlSlicer.cut("3"));
    for (int i = 0; i < SLICER_ITERATIONS; i++) {
        new Thread(new Runnable() {
            public void run() {
                assertEquals(Arrays.asList(new String[] { "1", "2", "3" }), xsl.asList());
                latch.countDown();/*from   www . j  av  a2  s.c  om*/
            }
        }).start();
    }
    latch.await();
}

From source file:com.hazelcast.hibernate.app.Executor.java

public void execute() throws Exception {
    CountDownLatch latch = new CountDownLatch(1000);
    int count;/*  w w  w  . j a  va 2  s.  com*/

    Session session = sessionFactory.openSession();
    try {
        Criteria criteria = session.createCriteria(DummyEntity.class);
        criteria.setProjection(Projections.rowCount());
        count = ((Long) criteria.uniqueResult()).intValue();
    } finally {
        session.close();
    }

    if (count == 0) {
        count = 200000;
        insertDummyEntities(count, 100);
    }

    try {
        for (int i = 0; i < latch.getCount(); i++) {
            executorService.submit(new Task(i, sessionFactory, 1000, latch));
        }

        latch.await(1, TimeUnit.DAYS);
    } finally {
        executorService.shutdown();
    }
}