Example usage for java.util.concurrent CountDownLatch countDown

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

Introduction

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

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

From source file:com.liferay.mobile.android.CookieAuthenticationTest.java

@Test
public void signIn() throws Exception {
    Session session = new SessionImpl(this.session);
    final JSONArray[] sites = { null };
    final CountDownLatch lock = new CountDownLatch(1);

    CookieSignIn.signIn(session, new CookieSignIn.CookieCallback() {

        @Override/*from   w  w w .ja  v a2 s  .  c o  m*/
        public void onSuccess(Session session) {
            try {
                GroupService service = new GroupService(session);
                sites[0] = service.getUserSitesGroups();
                lock.countDown();
            } catch (Exception e) {
                onFailure(e);
            }
        }

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

    });

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

From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java

@Test
public void testKilledSession() throws Exception {
    NodeCache cache = null;/*from  w w w.  j  a v a2 s .  c o  m*/
    Timing timing = new Timing();
    CuratorFramework client = null;
    try {
        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/test/node", "start".getBytes());

        cache = new NodeCache(client, "/test/node");
        cache.start(true);

        final CountDownLatch latch = new CountDownLatch(1);
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                latch.countDown();
            }
        });

        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        Thread.sleep(timing.multiple(1.5).session());

        Assert.assertEquals(cache.getCurrentData().getData(), "start".getBytes());

        client.setData().forPath("/test/node", "new data".getBytes());
        Assert.assertTrue(timing.awaitLatch(latch));
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.kurento.kmf.media.HttpGetEndpointAsyncTest.java

/**
 * Test for {@link MediaSessionStartedEvent}
 * /*from   w  w w.ja  va 2s . co  m*/
 * @throws InterruptedException
 */
@Test
public void testEventMediaSessionStarted() throws InterruptedException {

    final PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_SMALL).build();
    player.connect(httpEp);

    final CountDownLatch eosLatch = new CountDownLatch(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override
        public void onEvent(EndOfStreamEvent event) {
            eosLatch.countDown();
        }
    });

    final BlockingQueue<ListenerRegistration> events = new ArrayBlockingQueue<ListenerRegistration>(1);
    httpEp.addMediaSessionStartedListener(new MediaEventListener<MediaSessionStartedEvent>() {

        @Override
        public void onEvent(MediaSessionStartedEvent event) {
            player.play();
        }
    }, new Continuation<ListenerRegistration>() {

        @Override
        public void onSuccess(ListenerRegistration result) {
            events.add(result);
        }

        @Override
        public void onError(Throwable cause) {
            throw new KurentoMediaFrameworkException(cause);
        }
    });

    ListenerRegistration reg = events.poll(500, MILLISECONDS);
    Assert.assertNotNull(reg);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        // This should trigger MediaSessionStartedEvent
        httpclient.execute(new HttpGet(httpEp.getUrl()));
    } catch (ClientProtocolException e) {
        throw new KurentoMediaFrameworkException(e);
    } catch (IOException e) {
        throw new KurentoMediaFrameworkException(e);
    }

    try {
        eosLatch.await(500, MILLISECONDS);
    } catch (InterruptedException e) {
        player.release();
        throw new KurentoMediaFrameworkException(e);
    }

}

From source file:kieker.tools.resourceMonitor.ResourceMonitor.java

@Override
protected boolean performTask() {
    LOG.info(this.toString());

    final CountDownLatch cdl = new CountDownLatch(1);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/* w w  w.  ja  va 2 s .  c o  m*/
        public void run() {
            cdl.countDown();
        }
    });

    final Configuration controllerConfiguration;
    if (this.monitoringConfigurationFile != null) {
        controllerConfiguration = ConfigurationFactory
                .createConfigurationFromFile(this.monitoringConfigurationFile);
    } else {
        controllerConfiguration = ConfigurationFactory.createSingletonConfiguration();
    }
    this.monitoringController = MonitoringController.createInstance(controllerConfiguration);

    this.initSensors();
    LOG.info("Monitoring started");

    if (this.duration >= 0) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                cdl.countDown();
                timer.cancel();
            }
        }, TimeUnit.MILLISECONDS.convert(this.duration, this.durationUnit));
        LOG.info("Waiting for " + this.duration + " " + this.durationUnit + " timeout...");
    }

    try {
        LOG.info("Press Ctrl+c to terminate");
        cdl.await();
    } catch (final InterruptedException ex) {
        LOG.warn("The monitoring has been interrupted", ex);
        return false;
    } finally {
        LOG.info("Monitoring terminated");
    }

    return true;
}

From source file:com.vmware.photon.controller.rootscheduler.SchedulerDcpHostTest.java

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

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

    final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size());
    Operation.CompletionHandler handler = (operation, throwable) -> {
        latch.countDown();
    };/* w ww . j ava  2 s.c  o  m*/

    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.microsoft.office.core.ContactsAsyncTestCase.java

private void createAndCheck() throws Exception {
    prepareContact();/* w w w.ja va2 s . c om*/
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                assertTrue(StringUtils.isNotEmpty(contact.getId()));
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });

    cdl.await();
}

From source file:ch.windmobile.server.socialmodel.mogodb.HeavyLoadTest.java

public void testFullChatCycle() throws Exception {
    ServiceLocator locator = new MongoDBServiceLocator().connect(null);
    try {/* ww w . j a v a 2 s  .  c o  m*/
        final int CNT = 50000;
        final Executor executor = Executors.newFixedThreadPool(10);
        final ChatService chatService = locator.getService(ChatService.class);
        final AtomicInteger counter = new AtomicInteger();
        final CountDownLatch latch = new CountDownLatch(CNT);
        for (int i = 0; i < CNT; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    chatService.postMessage("TestRoom", "aUser",
                            "Hello, this is my message " + counter.incrementAndGet(), "");
                    latch.countDown();
                }
            });
        }
        System.out.println("Chat sent, waiting for the end...");
        latch.await(2, TimeUnit.MINUTES);
        Messages ret = chatService.findMessages("TEST", 5);
        System.out.println("result : " + ret);
    } finally {
        locator.disconnect();
    }
}

From source file:com.pinterest.rocksplicator.controller.DispatcherTest.java

@Test
public void testRetryTask() throws Exception {
    final String errorMsg = "Boom!!!";
    TaskBase task = new ThrowingTask(errorMsg).retry(3).getEntity();
    final CountDownLatch latch = new CountDownLatch(3);
    FIFOTaskQueue tq = new FIFOTaskQueue(10) {
        @Override/*  www.j  a v  a2 s.co m*/
        public boolean finishTask(final long id, final String output) {
            latch.countDown();
            return super.finishTask(id, output);
        }

        @Override
        public long finishTaskAndEnqueueRunningTask(final long id, final String output, final TaskBase newTask,
                final String worker) {
            latch.countDown();
            return super.finishTaskAndEnqueueRunningTask(id, output, newTask, worker);
        }
    };
    tq.enqueueTask(task, Integer.toString(++nameCounter), 0);

    Semaphore idleWorkersSemaphore = new Semaphore(2);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, tq);
    TaskDispatcher dispatcher = new TaskDispatcher(2, idleWorkersSemaphore, workerPool, tq);
    dispatcher.start();

    Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
    Assert.assertEquals(tq.getResult(0), errorMsg);
    Assert.assertEquals(tq.getResult(1), errorMsg);
    Assert.assertEquals(tq.getResult(2), errorMsg);
    dispatcher.stop();
}

From source file:com.baidu.oped.apm.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);

    UdpDataSender sender = new UdpDataSender("localhost", 9009, "test", 128, 1000, 1024 * 64 * 100) {
        @Override// w  w w . j  a  v a  2 s . c om
        protected boolean isLimit(int interBufferSize) {
            boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };
    try {
        sender.send(tbase);
        latch.await(5000, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

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

private void createAndCheck() throws Exception {
    prepareEvent();/*from w  w w  .  j a va 2s  .c o m*/
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(Void result) {
            try {
                assertTrue(StringUtils.isNotEmpty(EventsAsyncTestCase.this.event.getId()));
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });

    cdl.await();
}