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:de.da_sense.moses.client.com.NetworkJSON.java

/**
 * Goes through the stages INIT (get the ReqTaskExecutor and the prepare the return),
 * CONNECTING (Call doPost with the JSONObject in params[0] and parse the result into a
 * string), EXEPTION (only if an Exception occurred) and POSTEXECUTE (return the result)
 * and issues updates whenever it's reaching a new stage.
 *  //from   ww  w. ja v  a  2  s  . com
 * @param params One or more instances of APIRequest
 */
@Override
protected String doInBackground(NetworkJSON.APIRequest... params) {
    publishProgress(new BackgroundException(ConnectionParam.INIT, null));
    e = params[0].reqTaskExecutor;
    String ret = "";
    if (debug) {
        signal = new CountDownLatch(1);
        return response.generateAnswer(params[0].request);
    }
    try {
        publishProgress(new BackgroundException(ConnectionParam.CONNECTING, null));
        HttpResponse re = doPost(url, params[0].request);
        ret = EntityUtils.toString(re.getEntity());
    } catch (Exception e) {
        publishProgress(new BackgroundException(ConnectionParam.EXCEPTION, e));
    }
    publishProgress(new BackgroundException(ConnectionParam.POSTEXECUTE, null));
    return ret;
}

From source file:com.vmware.photon.controller.deployer.dcp.DeployerDcpServiceHostTest.java

private void waitForServicesStartup(DeployerDcpServiceHost host)
        throws TimeoutException, InterruptedException, NoSuchFieldException, IllegalAccessException {

    serviceSelfLinks = ServiceHostUtils.getServiceSelfLinks(
            DeployerDcpServiceHost.FACTORY_SERVICE_FIELD_NAME_SELF_LINK,
            DeployerDcpServiceHost.FACTORY_SERVICES);

    final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size());
    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override//from  ww w  . ja  v  a  2s .c o m
        public void handle(Operation completedOp, Throwable failure) {
            latch.countDown();
        }
    };

    String[] links = new String[serviceSelfLinks.size()];
    host.registerForServiceAvailability(handler, serviceSelfLinks.toArray(links));
    if (!latch.await(10, TimeUnit.SECONDS)) {
        throw new TimeoutException();
    }
}

From source file:com.onyxscheduler.domain.SchedulerIT.java

@Test(timeout = FIRE_THRESHOLD_TIMEOUT_IN_MILLIS)
public void shouldFireJobOnceWithPastDate() throws Scheduler.DuplicateJobKeyException, InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    latchProvider.setLatch(latch);//from w  ww.j a va2 s.  c  o m
    CountDownJob existingJob = buildJobWithFixedDateTrigger(buildPastDate());
    scheduler.scheduleJob(existingJob);
    latch.await();
}

From source file:org.kurento.repository.OneRecordingServer.java

private void prepareToUploadVideo(RepositoryItem repositoryItem) throws InterruptedException {

    RepositoryHttpRecorder recorder = repositoryItem.createRepositoryHttpRecorder("video-upload");

    log.info("The video must be uploaded with PUT or POST to the URL: " + recorder.getURL());

    readyToUploadWatch.countDown();//from w w  w  . ja v a 2  s . c  om

    recorder.setAutoTerminationTimeout(5 * 1000);
    log.info(
            "The recorder will be auto-terminated 5 seconds after the last uploading of content (http PUT or POST)");

    final CountDownLatch terminatedLatch = new CountDownLatch(1);

    recorder.addSessionStartedListener(new RepositoryHttpEventListener<HttpSessionStartedEvent>() {
        @Override
        public void onEvent(HttpSessionStartedEvent event) {
            log.info("Uploading started");
        }
    });

    recorder.addSessionTerminatedListener(new RepositoryHttpEventListener<HttpSessionTerminatedEvent>() {
        @Override
        public void onEvent(HttpSessionTerminatedEvent event) {
            log.info("Uploading terminated");
            terminatedLatch.countDown();
        }
    });

    terminatedLatch.await();
}

From source file:com.netflix.config.ConcurrentMapConfigurationTest.java

@Test
public void testConcurrency() {
    final ConcurrentMapConfiguration conf = new ConcurrentMapConfiguration();
    ExecutorService exectuor = Executors.newFixedThreadPool(20);
    final CountDownLatch doneSignal = new CountDownLatch(1000);
    for (int i = 0; i < 1000; i++) {
        final Integer index = i;
        exectuor.submit(new Runnable() {
            public void run() {
                conf.addProperty("key", index);
                conf.addProperty("key", "stringValue");
                doneSignal.countDown();/*  w  ww  .j  av a2s .  c o  m*/
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }
            }
        });
    }
    try {
        doneSignal.await();
    } catch (InterruptedException e) {

    }
    List prop = (List) conf.getProperty("key");
    assertEquals(2000, prop.size());
}

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

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

        public void onSuccess(Void result) {
            try {
                try {
                    updateAndCheck();
                } finally {
                    // clean up
                    removeMessage();
                }
            } 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:com.bj58.spat.gaea.server.util.async.AsyncWorker.java

private void execTimeoutTask() {
    try {/*w ww .  j  a  v a 2s  .  c  o m*/
        final AsyncTask task = taskQueue.take();
        if (task != null) {
            if ((System.currentTimeMillis() - task.getAddTime()) > task.getQtimeout()) {
                task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                return;
            } else {
                final CountDownLatch cdl = new CountDownLatch(1);
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Object obj = task.getHandler().run();
                            task.getHandler().messageReceived(obj);
                        } catch (Throwable ex) {
                            task.getHandler().exceptionCaught(ex);
                        } finally {
                            cdl.countDown();
                        }
                    }
                });
                cdl.await(getTimeout(task.getTimeout(), taskQueue.size()), TimeUnit.MILLISECONDS);
                if (cdl.getCount() > 0) {
                    task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                }
            }
        } else {
            logger.error("execTimeoutTask take task is null");
        }
    } catch (InterruptedException ie) {
        logger.error("");
    } catch (Throwable e) {
        logger.error("get task from poll error", e);
    }
}

From source file:com.gitpitch.services.OfflineService.java

public CountDownLatch fetchZip(PitchParams pp, Optional<SlideshowModel> ssmo) {

    log.debug("fetchZip: pp={}, ssmo.isPresent={}", pp, ssmo.isPresent());

    final String zipKey = MarkdownModel.genKey(pp);

    CountDownLatch freshLatch = new CountDownLatch(1);
    CountDownLatch activeLatch = zipLatchMap.putIfAbsent(zipKey, freshLatch);

    if (activeLatch != null) {
        /*/*from   www.j  a  v a2s . c o m*/
         * A non-null activeLatch implies a fetchZip()
         * operation is already in progress for the current
         * /{user}/{repo}?b={branch}.
         */
        log.debug("fetchZip: pp={}, already in progress, " + "returning existing activeLatch={}", pp,
                activeLatch);
        return activeLatch;

    } else {

        CompletableFuture<Void> syncFuture = CompletableFuture.supplyAsync(() -> {

            Path branchPath = diskService.ensure(pp);
            int zipStatus = generateZip(pp, ssmo);

            if (zipStatus != STATUS_OK) {
                log.warn("fetchZip: pp={}, fetch status={}", pp, zipStatus);
            }

            /*
             * Current operation completed, so remove latch associated
             * with operation from zipLatchMap to permit future
             * operations on this /{user}/{repo}?b={branch}.
             */
            releaseCountDownLatch(zipLatchMap, zipKey);

            /*
             * Operation completed, valid result cached, no return required.
             */
            return null;

        }, backEndThreads.POOL).handle((result, error) -> {

            if (error != null) {

                log.warn("fetchZip: pp={}, fetch error={}", pp, error);
                releaseCountDownLatch(zipLatchMap, zipKey);
            }

            return null;
        });

        return freshLatch;
    }

}

From source file:com.spotify.ffwd.AgentCore.java

private void waitUntilStopped(final Injector primary) throws InterruptedException {
    final CountDownLatch shutdown = new CountDownLatch(1);
    Runtime.getRuntime().addShutdownHook(setupShutdownHook(primary, shutdown));
    shutdown.await();//w w  w.ja  v  a 2 s  .  c o  m
}

From source file:com.anrisoftware.prefdialog.miscswing.dialogsworker.OpenDialogAction.java

/**
 * Opens the dialog on the AWT event thread and waits for the user to close
 * the dialog.//w  w  w .  j  a  va2 s. c  om
 * <p>
 * <h2>AWT Thread</h2>
 * Should be called <i>outside</i> the AWT event dispatch thread.
 * </p>
 *
 * @return the result value or {@code null}.
 */
@Override
public synchronized ResultType call() throws Exception {
    isTrue(!isEventDispatchThread(), "Cannot block the AWT event dispatch thread");
    notNull(dialogWorker, "dialogWorker");
    cursorWorker.setCursor(WAIT_CURSOR);
    DialogType dialog = createDialog(dialogWorker);
    dialogLatch = new CountDownLatch(1);
    openDialog(dialog, dialogWorker);
    cursorWorker.setCursor(DEFAULT_CURSOR);
    dialogLatch.await();
    return dialogResult;
}