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.sixt.service.framework.kafka.messaging.KafkaIntegrationTest.java

@Test
public void simpleProducerConsumer() throws InterruptedException {
    ServiceProperties serviceProperties = new ServiceProperties();
    serviceProperties.initialize(new String[] {}); // Reads environment variables set by DockerComposeHelper

    Topic ping = new Topic("ping");
    Topic pong = new Topic("pong");

    final int N = 10;

    Producer producer = new ProducerFactory(serviceProperties).createProducer();
    for (int i = 0; i < N; i++) {
        SayHelloToCmd cmd = SayHelloToCmd.newBuilder().setName(Integer.toString(i)).build();
        Message request = Messages.requestFor(ping, pong, RandomStringUtils.randomAscii(5), cmd,
                new OrangeContext());
        producer.send(request);/*from  w  w w.j a v  a2  s . co  m*/
    }

    final CountDownLatch requestLatch = new CountDownLatch(N);
    final CountDownLatch responseLatch = new CountDownLatch(N);

    TypeDictionary typeDictionary = new TypeDictionary();
    ReflectionTypeDictionaryFactory typeDictionaryFactory = new ReflectionTypeDictionaryFactory(null);
    typeDictionary.putAllParsers(typeDictionaryFactory.populateParsersFromClasspath());

    typeDictionary.putHandler(MessageType.of(SayHelloToCmd.class), new MessageHandler<SayHelloToCmd>() {
        @Override
        public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) {
            SayHelloToReply greeting = SayHelloToReply.newBuilder()
                    .setGreeting("Hello to " + message.getPayload().getName()).build();
            Message reply = Messages.replyTo(message, greeting, context);

            producer.send(reply);
            requestLatch.countDown();

        }
    });

    typeDictionary.putHandler(MessageType.of(SayHelloToReply.class), new MessageHandler<SayHelloToReply>() {
        @Override
        public void onMessage(Message<SayHelloToReply> message, OrangeContext context) {
            responseLatch.countDown();
        }
    });

    ConsumerFactory consumerFactory = new ConsumerFactory(serviceProperties, typeDictionary, null, null);
    Consumer requestConsumer = consumerFactory.consumerForTopic(ping, new DiscardFailedMessages());
    Consumer replyConsumer = consumerFactory.consumerForTopic(pong, new DiscardFailedMessages());

    assertTrue(requestLatch.await(60, TimeUnit.SECONDS));
    assertTrue(responseLatch.await(60, TimeUnit.SECONDS));

    producer.shutdown();
    requestConsumer.shutdown();
    replyConsumer.shutdown();
}

From source file:com.indeed.imhotep.web.ExecutionManager.java

/**
 * Keeps track of the query that is going to be executed and makes sure that user allocated limit is not exceeded.
 * When the query execution is completed (data is in HDFS cache) or fails, the returned Query object must be closed.
 *//*  w w  w  . j av a2  s  . co  m*/
public synchronized QueryTracker queryStarted(String query, String username) throws TimeoutException {
    final CountDownLatch releaseLock;
    final CountDownLatch waitLockForQuery;
    final Semaphore waitLockForUser;
    if (queryToLock.containsKey(query)) { // this is a duplicate query and execution will have to wait
        waitLockForQuery = queryToLock.get(query);
        waitLockForUser = null;
        releaseLock = null;
    } else { // this is a non-duplicate query and the lock has to be released after execution is finished
        waitLockForQuery = null;
        waitLockForUser = getUserSemaphore(username);
        releaseLock = new CountDownLatch(1);
        queryToLock.put(query, releaseLock);
    }
    final QueryTracker newQueryTracker = new QueryTracker(username, query, waitLockForQuery, waitLockForUser,
            releaseLock, this);
    runningQueries.add(newQueryTracker);
    return newQueryTracker;
}

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

@Override
public void startup() {
    log.info("Starting up the Interactive Spaces Master ROS context");

    startupLatch = new CountDownLatch(1);
    rosMasterController.setRosEnvironment(rosEnvironment);

    rosMasterController.addListener(new RosMasterControllerListener() {
        @Override/*from   ww  w.j  a  va 2s .c om*/
        public void onRosMasterStartup() {
            handleRosMasterStartup(startupLatch);
        }

        @Override
        public void onRosMasterShutdown() {
            // Don't care
        }
    });

    rosMasterController.startup();

    try {
        startupLatch.await();
    } catch (InterruptedException e) {
        SimpleInteractiveSpacesException.throwFormattedException("ROS Master Context Startup interrupted");
    }
}

From source file:net.java.html.charts.ChartsTest.java

/**
 *
 * @throws InterruptedException//from ww w .j  a v  a  2s. c o m
 */
@BeforeMethod
public void initializePresenter() throws InterruptedException {
    animationComplete = false;
    final CountDownLatch initialized = new CountDownLatch(1);
    final BrowserBuilder builder = BrowserBuilder.newBrowser().loadPage("charts.html").loadFinished(() -> {
        presenter = Fn.activePresenter();
        initialized.countDown();
    });
    Executors.newSingleThreadExecutor().execute(builder::showAndWait);
    initialized.await();
    assertNotNull(presenter, "We have the presenter");
}

From source file:gobblin.compliance.restore.ComplianceRestoreJob.java

public void run() throws IOException {
    Preconditions.checkNotNull(this.finder, "Dataset finder class is not set");
    List<Dataset> datasets = this.finder.findDatasets();
    this.finishCleanSignal = Optional.of(new CountDownLatch(datasets.size()));
    for (final Dataset dataset : datasets) {
        ListenableFuture<Void> future = this.service.submit(new Callable<Void>() {
            @Override/*www  . j a v  a 2  s.  co  m*/
            public Void call() throws Exception {
                if (dataset instanceof RestorableDataset) {
                    log.info("Trying to restore");
                    ((RestorableDataset) dataset).restore();
                } else {
                    log.warn("Not an instance of " + RestorableDataset.class + " Dataset won't be restored "
                            + dataset.datasetURN());
                }
                return null;
            }
        });
        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void result) {
                ComplianceRestoreJob.this.finishCleanSignal.get().countDown();
                log.info("Successfully restored: " + dataset.datasetURN());
            }

            @Override
            public void onFailure(Throwable t) {
                ComplianceRestoreJob.this.finishCleanSignal.get().countDown();
                log.warn("Exception caught when restoring " + dataset.datasetURN() + ".", t);
                ComplianceRestoreJob.this.throwables.add(t);
                ComplianceRestoreJob.this.eventSubmitter.submit(ComplianceEvents.Restore.FAILED_EVENT_NAME,
                        ImmutableMap.of(ComplianceEvents.FAILURE_CONTEXT_METADATA_KEY,
                                ExceptionUtils.getFullStackTrace(t), ComplianceEvents.DATASET_URN_METADATA_KEY,
                                dataset.datasetURN()));
            }
        });
    }
}

From source file:com.vladmihalcea.OptimisticLockingTest.java

@Test
public void testRetries() throws InterruptedException {
    final Product product = productService.newProduct();
    assertEquals(0, product.getVersion());
    Product savedProduct = productService.updateName(product.getId(), "name");
    assertEquals(1, savedProduct.getVersion());

    final int threadsNumber = 10;

    final AtomicInteger atomicInteger = new AtomicInteger();
    final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1);
    final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1);

    for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) {
        final long index = (long) atomicInteger.get() * threadsNumber;
        LOGGER.info("Scheduling thread index {}", index);
        Thread testThread = new Thread(new Runnable() {
            @Override//from w w  w .  ja v  a 2  s . co m
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(product.getId(), UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.error("Exception thrown!", e);
                } finally {
                    endLatch.countDown();
                }
            }
        });
        testThread.start();
    }
    startLatch.countDown();
    LOGGER.info("Waiting for threads to be done");
    endLatch.countDown();
    endLatch.await();
    LOGGER.info("Threads are done");
}

From source file:com.frostwire.android.tests.vuze.VuzeDownloadTest.java

@LargeTest
public void testDownload1() throws IOException, TOTorrentException {

    HttpClient c = HttpClientFactory.newInstance();

    File torrentFile = new File(SystemUtils.getTorrentsDirectory(), "download_test1.torrent");
    File saveDir = SystemUtils.getTorrentDataDirectory();
    c.save(TorrentUrls.FROSTCLICK_BRANDON_HINES_2010, torrentFile);

    TOTorrent t = readTorrent(torrentFile.getAbsolutePath());

    VuzeUtils.remove(t.getHash(), true);
    TestUtils.sleep(10000);/*from  w ww  .  j a  v  a  2s  .  c  o m*/

    final CountDownLatch signal = new CountDownLatch(1);

    VuzeDownloadManager dm = VuzeDownloadFactory.create(torrentFile.getAbsolutePath(), null,
            saveDir.getAbsolutePath(), new VuzeDownloadListener() {

                @Override
                public void stateChanged(VuzeDownloadManager dm, int state) {
                    LOG.info("testDownload1-stateChanged:" + formatDownloadState(state));
                }

                @Override
                public void downloadComplete(VuzeDownloadManager dm) {
                    signal.countDown();
                }
            });

    assertNotNull(dm);

    assertTrue("Download not finished", TestUtils.await(signal, 1, TimeUnit.HOURS));
}

From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java

private static void updateBbox() {

    try {//from  ww w  . j  a  v a  2  s  .co  m
        Connection conn = getConnection();
        String sql = "SELECT pid from objects where bbox is null limit 200000;";
        logger.info("loading bbox ...");
        Statement s1 = conn.createStatement();
        ResultSet rs1 = s1.executeQuery(sql);

        LinkedBlockingQueue<String[]> data = new LinkedBlockingQueue<String[]>();
        while (rs1.next()) {
            data.put(new String[] { rs1.getString("pid") });
        }

        CountDownLatch cdl = new CountDownLatch(data.size());

        BboxThread[] threads = new BboxThread[CONCURRENT_THREADS];
        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j] = new BboxThread(data, cdl, getConnection().createStatement());
            threads[j].start();
        }

        cdl.await();

        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j].s.close();
            threads[j].interrupt();
        }
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return;
}

From source file:adb4j.executor.CmdExecutor.java

/**
 * Runs a general command and wait for it to exit.
 *
 * @param command The command you want to run
 * @return//ww w .  j ava 2s. c o  m
 * @throws IOException
 * @see CmdResult
 * @see runAsync
 */
public CmdResult run(String command) throws IOException {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    defaultHandler.countDownLatch = Optional.of(countDownLatch);

    runAsync(command, defaultHandler, false);

    try {
        countDownLatch.await();
    } catch (InterruptedException ex) {
    }
    return new CmdResult(exitValue, exception, defaultHandler.getOutputStream(),
            defaultHandler.getErrorStream());
}

From source file:de.codesourcery.eve.skills.ui.utils.ParallelUITasksRunner.java

public static boolean submitParallelTasks(final ApplicationThreadManager threadManager, final UITask parent,
        UITask... children) {/*  ww w . ja v a 2 s  .  co m*/
    final AtomicInteger childSuccesses = new AtomicInteger(0);
    final AtomicInteger childFailures = new AtomicInteger(0);

    if (parent == null) {
        throw new IllegalArgumentException("parent task cannot be NULL");
    }

    if (ArrayUtils.isEmpty(children)) {
        throw new IllegalArgumentException("Need to provide at least one child task");
    }
    final CyclicBarrier startBarrier = new CyclicBarrier(children.length + 1) {
        @Override
        public void reset() {
            System.out.println("========== resetting start barrier =========== ");
            super.reset();
        }
    };

    final CountDownLatch childrenTerminated = new CountDownLatch(children.length);

    int submittedChildren = 0;
    for (final UITask child : children) {

        final UITask wrapped = new UITask() {

            @Override
            public void successHook() throws Exception {
                boolean success = false;
                try {
                    child.successHook();
                    success = true;
                } finally {
                    if (success) {
                        childSuccesses.incrementAndGet();
                    } else {
                        childFailures.incrementAndGet();
                    }
                    childrenTerminated.countDown();
                }
            }

            @Override
            public void beforeExecution() {
                child.beforeExecution();
                // note: when this method throws an exception , #failure() is invoked
            }

            @Override
            public void setEnabledHook(boolean yesNo) {
                child.setEnabledHook(yesNo);

            }

            @Override
            public void failureHook(Throwable t) throws Exception {
                try {
                    child.failureHook(t);
                } finally {
                    childFailures.incrementAndGet();
                    childrenTerminated.countDown();
                }
            }

            @Override
            public void cancellationHook() {
                try {
                    child.cancellationHook();
                } finally {
                    childFailures.incrementAndGet();
                    childrenTerminated.countDown();
                }
            }

            @Override
            public String getId() {
                return child.getId();
            }

            @Override
            public void run() throws Exception {
                try {
                    if (log.isTraceEnabled()) {
                        log.trace("run(): Child task " + getId() + " is now waiting.");
                    }
                    startBarrier.await(); // will BrokenBarrierException if any of the child tasks could not be started,
                } catch (InterruptedException e) {
                    log.error("run(): Child task " + getId() + " was interrupted");
                    Thread.currentThread().interrupt();
                } catch (BrokenBarrierException e) {
                    log.error("run(): Child task" + getId() + " aborted, barrier broken.");
                    throw new RuntimeException(
                            "Child task not started because another child task failed submitTask()");
                }

                if (log.isTraceEnabled()) {
                    log.trace("run(): Child task " + getId() + " is now running.");
                }
                child.run();
            }
        };

        if (null == threadManager.submitTask(wrapped, false)) {
            log.error("submitParallelTasks(): Failed to submit child " + child);

            // note: I wait for (submittedChildren-childFailures) because some 
            // child task may have already failed before reaching their run() method
            while (startBarrier.getNumberWaiting() != (submittedChildren - childFailures.get())) {
                log.info("submitParallelTasks(): Waiting for all child tasks to reach barrier ( "
                        + startBarrier.getNumberWaiting() + " waiting)");
                try {
                    java.lang.Thread.sleep(500);
                } catch (Exception e) {
                }
                ;
            }

            startBarrier.reset(); // will cause all child threads waiting on this barrier to terminate
            return false;
        }
        submittedChildren++;
    }

    /*
     * All children are submitted and waiting at the barrier.
     */
    final boolean parentSubmitted = null != threadManager.submitTask("Control thread of " + parent.getId(),
            new Runnable() {

                @Override
                public void run() {
                    try {

                        while (true) {
                            try {
                                log.debug("run(): Parent task " + parent.getId()
                                        + " is waiting for it's children to start...");
                                startBarrier.await(5, TimeUnit.SECONDS);
                                break;
                            } catch (TimeoutException e) {
                                if (childFailures.get() != 0) {
                                    runFailureHookOnEDT(parent,
                                            childFailures.get() + " child tasks of parent task "
                                                    + parent.getId() + " failed to start.");
                                    return;
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        runFailureHookOnEDT(parent, "Parent task " + parent.getId()
                                + " was interrupted while waiting" + " for it's children to start.");
                        startBarrier.reset(); // let children fail.
                        Thread.currentThread().interrupt();
                        return;
                    } catch (BrokenBarrierException e) {
                        runFailureHookOnEDT(parent,
                                "Parent task " + parent.getId() + " failed to wait for it's children");
                        throw new RuntimeException("Internal error - task " + parent.getId()
                                + " failed to wait for it's children?");
                    }

                    log.debug("run(): Task " + parent.getId() + " is waiting for it's children to finish");
                    try {
                        childrenTerminated.await();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        runFailureHookOnEDT(parent, "Parent task " + parent.getId()
                                + " was interrupted while waiting for it's children");
                        return;
                    }

                    log.info("run(): All children of parent task " + parent.getId()
                            + " have finished ( success: " + childSuccesses.get() + " / failure: "
                            + childFailures.get() + ")");

                    if (childFailures.get() > 0) {
                        runFailureHookOnEDT(parent, childFailures.get() + " child tasks of parent "
                                + parent.getId() + " have FAILED.");
                        return;
                    }

                    if (null == threadManager.submitTask(parent, false)) {
                        runFailureHookOnEDT(parent, "Failed to submit parent task " + parent.getId());
                        return;
                    }

                }
            }, false);

    if (!parentSubmitted) {
        log.debug("submitParallelTasks(): Failed to submit parent task " + parent.getId()
                + " , terminating child tasks.");
        startBarrier.reset(); // aborts all child tasks with a BrokenBarrierException
    }

    return parentSubmitted;
}