Example usage for java.util.concurrent CountDownLatch await

List of usage examples for java.util.concurrent CountDownLatch await

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch await.

Prototype

public void await() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted .

Usage

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_post_load_interceptors() throws Exception {

    CompleteBean entity = builder().randomId().name("DuyHai").label("label").buid();

    asyncManager.insert(entity).getImmediately();

    final CountDownLatch latch = new CountDownLatch(1);

    final AchillesFuture<CompleteBean> future = asyncManager.find(CompleteBean.class, entity.getId(),
            withAsyncListeners(new FutureCallback<Object>() {
                @Override/*from  w w  w  .j  ava2  s . co m*/
                public void onSuccess(Object result) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable t) {

                }
            }));

    latch.await();

    assertThat(future.get().getLabel()).isEqualTo("postLoad");
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_post_load_interceptor_on_typed_query() throws Exception {
    // Given/*from   w  ww.j ava2 s  .co  m*/
    CompleteBean entity = builder().randomId().name("DuyHai").label("label").buid();

    asyncManager.insert(entity).getImmediately();

    RegularStatement statement = select().from("CompleteBean").where(eq("id", bindMarker()));

    // When
    final CountDownLatch latch = new CountDownLatch(1);
    final AchillesFuture<CompleteBean> future = asyncManager
            .typedQuery(CompleteBean.class, statement, entity.getId()).getFirst(new FutureCallback<Object>() {
                @Override
                public void onSuccess(Object result) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable t) {

                }
            });

    latch.await();

    // Then
    assertThat(future.get().getLabel()).isEqualTo("postLoad");
}

From source file:com.netflix.curator.framework.imps.TestFrameworkBackground.java

@Test
public void testRetries() throws Exception {
    final int SLEEP = 1000;
    final int TIMES = 5;

    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryNTimes(TIMES, SLEEP));
    try {/*from   ww  w .j  av a2  s .  com*/
        client.start();
        client.getZookeeperClient().blockUntilConnectedOrTimedOut();

        final CountDownLatch latch = new CountDownLatch(TIMES);
        final List<Long> times = Lists.newArrayList();
        final AtomicLong start = new AtomicLong(System.currentTimeMillis());
        ((CuratorFrameworkImpl) client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() {
            @Override
            public void listen(OperationAndData<?> data) {
                if (data.getOperation().getClass().getName().contains("CreateBuilderImpl")) {
                    long now = System.currentTimeMillis();
                    times.add(now - start.get());
                    start.set(now);
                    latch.countDown();
                }
            }
        };

        server.stop();
        client.create().inBackground().forPath("/one");

        latch.await();

        for (long elapsed : times.subList(1, times.size())) // first one isn't a retry
        {
            Assert.assertTrue(elapsed >= SLEEP, elapsed + ": " + times);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.bt.aloha.util.ConcurrentUpdateManagerTest.java

@Test
public void testConcurrentUpdateConflictAwawreExceptionAbsorbed() throws Exception {
    // setup/*from w  ww .  j  a va  2s .co  m*/
    final CountDownLatch firstWriterRead = new CountDownLatch(1);
    final CountDownLatch secondWriterWrote = new CountDownLatch(1);
    final AtomicInteger failuresCounter = new AtomicInteger();

    ConcurrentUpdateBlock concurrentUpdateBlock = new ConflictAwareConcurrentUpdateBlock() {
        public void execute() {
            DialogInfo di = dialogCollection.get(dialogId);
            log.debug("First writer read");
            firstWriterRead.countDown();

            di.setApplicationData("first");
            log.debug("Waiting for second writer to write");
            try {
                secondWriterWrote.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            dialogCollection.replace(di);
            log.debug("First writer replaced");
        }

        public String getResourceId() {
            return dialogId;
        }

        public void onConcurrentUpdateConflict() {
            failuresCounter.incrementAndGet();
            throw new RuntimeException("bugger off");
        }
    };

    Runnable competingWriter = new Runnable() {
        public void run() {
            log.debug("Waiting for first writer to read");
            try {
                firstWriterRead.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            DialogInfo di = dialogCollection.get(dialogId);
            di.setApplicationData("second");
            dialogCollection.replace(di);
            log.debug("Second writer replaced");
            secondWriterWrote.countDown();
        }
    };

    // act
    new Thread(competingWriter).start();
    concurrentUpdateManager.executeConcurrentUpdate(concurrentUpdateBlock);

    // assert
    assertEquals(1, failuresCounter.get());
    assertEquals("first", dialogCollection.get(dialogId).getApplicationData());
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_post_load_interceptor_on_raw_typed_query() throws Exception {
    // Given//  w  w  w.java 2s  .c om
    CompleteBean entity = builder().randomId().name("DuyHai").label("label").buid();

    asyncManager.insert(entity).getImmediately();

    RegularStatement statement = select().from("CompleteBean").where(eq("id", bindMarker()));

    // When
    final CountDownLatch latch = new CountDownLatch(1);

    final AchillesFuture<CompleteBean> future = asyncManager
            .rawTypedQuery(CompleteBean.class, statement, entity.getId())
            .getFirst(new FutureCallback<Object>() {
                @Override
                public void onSuccess(Object result) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable t) {

                }
            });

    latch.await();

    // Then
    assertThat(future.get().getLabel()).isEqualTo("postLoad");
}

From source file:com.frostwire.AzureusStarter.java

private static synchronized void azureusInit() {

    try {//  ww  w  .ja v a2  s.c  om
        if (isAzureusCoreStarted()) {
            LOG.debug("azureusInit(): core already started. skipping.");
            return;
        }
    } catch (Exception ignore) {
    }

    Application.setApplication(
            CommonUtils.getUserSettingsDir().getAbsolutePath() + File.separator + "appwork" + File.separator);
    File jdHome = new File(
            CommonUtils.getUserSettingsDir().getAbsolutePath() + File.separator + "jd_home" + File.separator);
    if (!jdHome.exists()) {
        jdHome.mkdir();
    }
    JDUtilities.setJDHomeDirectory(jdHome);
    JDUtilities.getConfiguration().setProperty("DOWNLOAD_DIRECTORY",
            SharingSettings.TORRENT_DATA_DIR_SETTING.getValue().getAbsolutePath());

    File azureusUserPath = new File(
            CommonUtils.getUserSettingsDir() + File.separator + "azureus" + File.separator);
    if (!azureusUserPath.exists()) {
        azureusUserPath.mkdirs();
    }

    System.setProperty("azureus.loadplugins", "0"); // disable third party azureus plugins
    System.setProperty("azureus.config.path", azureusUserPath.getAbsolutePath());
    System.setProperty("azureus.install.path", azureusUserPath.getAbsolutePath());

    if (!AzureusCoreFactory.isCoreAvailable()) {
        //This does work
        org.gudy.azureus2.core3.util.SystemProperties.APPLICATION_NAME = "azureus";

        org.gudy.azureus2.core3.util.SystemProperties.setUserPath(azureusUserPath.getAbsolutePath());

        if (!SharingSettings.TORRENTS_DIR_SETTING.getValue().exists()) {
            SharingSettings.TORRENTS_DIR_SETTING.getValue().mkdirs();
        }

        COConfigurationManager.setParameter("Auto Adjust Transfer Defaults", false);
        COConfigurationManager.setParameter("General_sDefaultTorrent_Directory",
                SharingSettings.TORRENTS_DIR_SETTING.getValue().getAbsolutePath());

        try {
            AZUREUS_CORE = AzureusCoreFactory.create();
        } catch (AzureusCoreException coreException) {
            //so we already had one eh...
            if (AZUREUS_CORE == null) {
                AZUREUS_CORE = AzureusCoreFactory.getSingleton();
            }
        }

        //to guarantee a synchronous start
        final CountDownLatch signal = new CountDownLatch(1);

        AZUREUS_CORE.addLifecycleListener(new AzureusCoreLifecycleListener() {

            @Override

            public boolean syncInvokeRequired() {
                return false;
            }

            @Override
            public void stopping(AzureusCore core) {
                core.getGlobalManager().pauseDownloads();
            }

            @Override
            public void stopped(AzureusCore core) {
            }

            @Override
            public boolean stopRequested(AzureusCore core) throws AzureusCoreException {
                return false;
            }

            @Override
            public void started(AzureusCore core) {
                signal.countDown();
            }

            @Override
            public boolean restartRequested(AzureusCore core) throws AzureusCoreException {
                return false;
            }

            @Override
            public boolean requiresPluginInitCompleteBeforeStartedEvent() {
                return false;
            }

            @Override
            public void componentCreated(AzureusCore core, AzureusCoreComponent component) {
            }
        });

        if (!AZUREUS_CORE.isStarted() && !AZUREUS_CORE.isRestarting()) {
            AZUREUS_CORE.start();
        }

        AZUREUS_CORE.getGlobalManager().resumeDownloads();

        LOG.debug("azureusInit(): core.start() waiting...");
        try {
            signal.await();
            LOG.debug("azureusInit(): core started...");
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
    }
}

From source file:com.github.sdbg.debug.core.internal.webkit.protocol.WebkitDom.java

public WebkitNode getDocumentSync() throws IOException {
    @SuppressWarnings("unchecked")
    final WebkitResult<WebkitNode>[] result = new WebkitResult[1];
    final CountDownLatch latch = new CountDownLatch(1);

    getDocument(new WebkitCallback<WebkitNode>() {
        @Override//w ww. j  av  a 2  s  .co m
        public void handleResult(WebkitResult<WebkitNode> r) {
            result[0] = r;

            latch.countDown();
        }
    });

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

    }

    if (result[0].isError()) {
        throw new IOException(result[0].getErrorMessage());
    } else {
        return result[0].getResult();
    }
}

From source file:ch.cyberduck.cli.Terminal.java

protected Exit edit(final SessionPool session, final Path remote) throws BackgroundException {
    final EditorFactory factory = EditorFactory.instance();
    final Application application;
    final ApplicationFinder finder = ApplicationFinderFactory.get();
    if (StringUtils.isNotBlank(input.getOptionValue(TerminalOptionsBuilder.Params.application.name()))) {
        application = finder//  w ww  .j ava  2s  .c  o m
                .getDescription(input.getOptionValue(TerminalOptionsBuilder.Params.application.name()));
        if (!finder.isInstalled(application)) {
            throw new BackgroundException(LocaleFactory.localizedString("Unknown"),
                    String.format("Application %s not found",
                            input.getOptionValue(TerminalOptionsBuilder.Params.application.name())));
        }
    } else {
        application = factory.getEditor(remote.getName());
    }
    if (!finder.isInstalled(application)) {
        throw new BackgroundException(LocaleFactory.localizedString("Unknown"),
                String.format("No application found to edit %s", remote.getName()));
    }
    final Editor editor = factory.create(controller, session, application, remote);
    final CountDownLatch lock = new CountDownLatch(1);
    final Worker<Transfer> worker = editor.open(new ApplicationQuitCallback() {
        @Override
        public void callback() {
            lock.countDown();
        }
    }, new DisabledTransferErrorCallback(), new DefaultEditorListener(controller, session, editor));
    final SessionBackgroundAction<Transfer> action = new TerminalBackgroundAction<Transfer>(controller, session,
            worker);
    if (!this.execute(action)) {
        return Exit.failure;
    }
    try {
        lock.await();
    } catch (InterruptedException e) {
        return Exit.failure;
    }
    return Exit.success;
}

From source file:com.bt.aloha.batchtest.BatchTest.java

public void run(String scenarioName) {
    this.numberCompleted = 0;
    this.numberSucceeded = 0;
    this.results = new ConcurrentHashMap<String, Result>();
    normalizeWeightings();/*from   w  w w  .  j  a v a2  s  .com*/
    totalTime = 0;
    CyclicBarrier barrier = new CyclicBarrier(numberOfConcurrentStarts);
    for (int i = 0; i < numberOfRuns; i++) {
        try {
            if (manager != null)
                manager.doApplicationContextStartStop();
            long startTime = System.currentTimeMillis();
            Thread.sleep(1000);
            String[] beans = new String[numberOfConcurrentStarts];
            BatchTestScenario[] concurrentScenarios = new BatchTestScenario[numberOfConcurrentStarts];
            for (int j = 0; j < numberOfConcurrentStarts; j++) {
                beans[j] = scenarioName == null ? pickScenarioName() : scenarioName;

                BatchTestScenario s = (BatchTestScenario) applicationContext.getBean(beans[j]);
                ((BatchTestScenarioBase) s).setCallCollection(callCollection);
                ((BatchTestScenarioBase) s).setAudioFileUri(audioFileUri);

                if (s.getBatchTestScenarioResultListener() == null)
                    s.setBatchTestScenarioResultListener(this);
                concurrentScenarios[j] = s;
            }

            CountDownLatch latch = new CountDownLatch(numberOfConcurrentStarts);
            for (int j = 0; j < numberOfConcurrentStarts; j++) {
                if (concurrentScenarios[j] == null)
                    break;
                RunScenario rs = new RunScenario(concurrentScenarios[j], beans[j], barrier, latch);
                executorService.execute(rs);
            }
            latch.await();
            barrier.reset();
            totalTime += System.currentTimeMillis() - startTime;
        } catch (Throwable t) {
            log.error(String.format("Test run %d threw an exception", i), t);
        }
    }

    waitForAllToFinish(maximumScenarioCompletionWaitTimeSeconds);
    log.info("Finishing...");
    if (results.size() < 1) {
        log.info("NO scenarios run!");
        return;
    }
    numberSucceeded = 0;
    for (String o : results.keySet()) {
        String scenario = o.split(":")[0];
        Result res = results.get(o);
        Analysis result = analysis.get(scenario);
        if (result != null) {
            if (res.isSucceeded()) {
                result.setSuccessCount(result.getSuccessCount() + 1);
            } else {
                result.setFailureCount(result.getFailureCount() + 1);
            }
            log.info(String.format("Scenario %s %s", o, res.toString()));
            System.err.println(String.format("Scenario %s %s", o, res.toString()));
            numberCompleted++;
            if (res.isSucceeded())
                numberSucceeded++;
            else
                failedScenarios.add(o);
        } else {
            log.error("unable to find result for scenario " + scenario);
        }
    }
    log.info(numberSucceeded + " successful scenarios, " + successRate() + "% passed");
    log.info(numberCompleted());
    if (manager != null) {
        log.info("Access to ApplicationContext1 #: " + manager.getCountReturnedAppCtx1());
        log.info("Access to ApplicationContext2 #: " + manager.getCountReturnedAppCtx2());
    }
    resetDb();
}