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.basho.riak.client.http.util.logging.ConcurrentLoggingTest.java

/**
 * Test method for/*from   ww w  . ja  va2  s.co  m*/
 * {@link com.basho.riak.client.http.util.logging.LogNoHttpResponseRetryHandler#retryMethod(org.apache.commons.httpclient.HttpMethod, java.io.IOException, int)}
 * .
 * 
 * @throws InterruptedException
 */
@Test
public void retry_concurrentLogAndDump() throws InterruptedException {
    // create a bunch of threads
    // each must log 10 statements and call flush
    // ALL the statements must be present BUT ONCE in
    // the mock delegate appender (order does not matter)
    final int numThreads = 10;
    final LogNoHttpResponseRetryHandler handler = new LogNoHttpResponseRetryHandler();
    ExecutorService es = Executors.newFixedThreadPool(numThreads);
    List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(numThreads);

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch dumpLatch = new CountDownLatch(10);

    for (int i = 0; i < numThreads; i++) {
        final int threadCounter = i;
        tasks.add(new Callable<Void>() {

            @Override
            public Void call() {
                Logger logger = Logger.getLogger("httpclient.wire");
                try {
                    startLatch.await();

                    for (int j = 0; j < 10; j++) {
                        logger.debug(String.format(MESSAGE, new Object[] { threadCounter, j }));
                    }

                    dumpLatch.countDown();
                    dumpLatch.await();

                    handler.retryMethod(new GetMethod(), new NoHttpResponseException(), 0);

                    return null;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    startLatch.countDown();
    es.invokeAll(tasks);

    verify(mockLogger, times(100)).callAppenders(logEventCaptor.capture());

    TreeSet<Integer> check = new TreeSet<Integer>();

    for (LoggingEvent le : logEventCaptor.getAllValues()) {
        // verify that each of Thread:Iter is present for 0-90-9
        int loc = Integer.parseInt(le.getMessage().toString());
        check.add(loc);
    }

    assertEquals(100, check.size());
    assertEquals(0, (int) check.first());
    assertEquals(99, (int) check.last());
}

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

@Test
public void testWithNamespaceAndLostSession() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
            .retryPolicy(new ExponentialBackoffRetry(100, 3)).namespace("aisa").build();
    try {//from   ww w .j a  v a  2s . c o m
        client.start();

        client.create().forPath("/test-me");

        final CountDownLatch latch = new CountDownLatch(1);
        final Semaphore semaphore = new Semaphore(0);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) {
                    semaphore.release();
                } else if (newState == ConnectionState.RECONNECTED) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        server.stop();

        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        try {
            client.delete().guaranteed().forPath("/test-me");
            Assert.fail();
        } catch (KeeperException.ConnectionLossException e) {
            // expected
        }
        Assert.assertTrue(timing.acquireSemaphore(semaphore));

        timing.sleepABit();

        server = new TestingServer(server.getPort(), server.getTempDirectory());
        Assert.assertTrue(timing.awaitLatch(latch));

        timing.sleepABit();

        Assert.assertNull(client.checkExists().forPath("/test-me"));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

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

@Test
public void testWithNamespaceAndLostSessionAlt() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
            .retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
    try {//from   ww  w  .  j ava 2 s .  com
        client.start();

        CuratorFramework namespaceClient = client.usingNamespace("foo");
        namespaceClient.create().forPath("/test-me");

        final CountDownLatch latch = new CountDownLatch(1);
        final Semaphore semaphore = new Semaphore(0);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) {
                    semaphore.release();
                } else if (newState == ConnectionState.RECONNECTED) {
                    latch.countDown();
                }
            }
        };
        namespaceClient.getConnectionStateListenable().addListener(listener);
        server.stop();

        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        try {
            namespaceClient.delete().guaranteed().forPath("/test-me");
            Assert.fail();
        } catch (KeeperException.ConnectionLossException e) {
            // expected
        }
        Assert.assertTrue(timing.acquireSemaphore(semaphore));

        timing.sleepABit();

        server = new TestingServer(server.getPort(), server.getTempDirectory());
        Assert.assertTrue(timing.awaitLatch(latch));

        timing.sleepABit();

        Assert.assertNull(namespaceClient.checkExists().forPath("/test-me"));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.nesscomputing.service.discovery.client.internal.ServiceDiscoveryReader.java

@Override
void visit(final List<String> childNodes, final ZooKeeper zookeeper, final long tick)
        throws InterruptedException {
    final Map<String, List<ServiceInformation>> serviceMap = new HashMap<String, List<ServiceInformation>>();

    if (!childNodes.isEmpty()) {
        final List<ServiceInformation> rawServices = new ArrayList<ServiceInformation>(childNodes.size());
        final CountDownLatch latch = new CountDownLatch(childNodes.size());

        final long now = System.nanoTime();

        for (final String child : childNodes) {

            final String childPath = getNodePath(child);

            if (badNodes.containsKey(childPath)) {
                final Long penaltyEndsTime = badNodes.get(childPath);
                if (penaltyEndsTime != null && penaltyEndsTime > now) {
                    // Decrement the countdown latch, because there will be no callback for this
                    // node.
                    latch.countDown();
                    // Ignore a bad node for a while.
                    continue;
                }/*from ww  w. j ava 2s . co  m*/
                LOG.info("Unmarking %s as a bad node!", childPath);
                badNodes.remove(childPath);
            }

            zookeeper.getData(childPath, false, new DataCallback() {
                @Override
                public void processResult(final int rc, final String path, final Object ctx, final byte[] data,
                        final Stat stat) {

                    ServiceInformation si = null;
                    try {
                        if (data != null && data.length > 0) {
                            si = objectMapper.readValue(data, ServiceInformation.class);
                            LOG.trace("%s contains %s", path, si);
                        } else {
                            // This can sometimes happen if a node that we want to inspect
                            // disappears between callback post and callback processing.
                            LOG.trace("Got callback but no data!");
                        }

                    } catch (IOException ioe) {
                        LOG.debug(ioe, "While deserializing %s", new String(data, Charsets.UTF_8));
                        LOG.info("Marking %s as a bad node!", path);
                        // Put a bad node into the penalty box.
                        badNodes.put(path, now + penaltyTime);
                    } finally {
                        synchronized (rawServices) {
                            if (si != null) {
                                rawServices.add(si);
                            }
                        }
                        latch.countDown();
                    }
                }
            }, null);
        }

        if (!latch.await(discoveryConfig.getZookeeperTimeout().getMillis(), TimeUnit.MILLISECONDS)) {
            LOG.warn("Timeout waiting for callbacks, some nodes were not parsed.");
        }

        // Make sure that even with late callbacks, this will not throw spurious ConcurrentModificationExceptions
        synchronized (rawServices) {
            for (final ServiceInformation si : rawServices) {
                List<ServiceInformation> services = serviceMap.get(si.getServiceName());
                if (services == null) {
                    services = new ArrayList<ServiceInformation>();
                    serviceMap.put(si.getServiceName(), services);
                }
                services.add(si);
            }
        }
    }

    Map<String, ConsistentRingGroup> serviceGroups = Maps.newHashMap();
    for (Map.Entry<String, List<ServiceInformation>> entry : serviceMap.entrySet()) {
        ConsistentRingGroup currentGroup = stateHolder.getState().get(entry.getKey());
        //Rebuilding a group is kind of expensive, so reuse the old group if it hasn't changed
        if (currentGroup != null
                && Sets.newHashSet(entry.getValue()).equals(Sets.newHashSet(currentGroup.getAll()))) {
            serviceGroups.put(entry.getKey(), currentGroup);
        } else {
            serviceGroups.put(entry.getKey(), new ConsistentRingGroup(entry.getValue()));
        }
    }
    stateHolder.setState(serviceGroups);
}

From source file:org.wisdom.framework.vertx.FileUploadTest.java

@Test
public void testFileUploadOfSmallFilesWithAsyncDownload() throws InterruptedException, IOException {
    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("request.body.max.size", 100 * 1024)).thenReturn(100 * 1024);
    when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE))
            .thenReturn(DiskFileUpload.MINSIZE);
    when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(-1l);
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            final FileItem item = context().file("upload");
            if (!item.isInMemory()) {
                return badRequest("In memory expected");
            }/*from   www.ja va2 s .c o  m*/
            if (!item.name().equals("my-file.dat")) {
                return badRequest("broken name");
            }
            if (item.size() != 2048) {
                return badRequest("broken file");
            }

            if (!context().form().get("comment").get(0).equals("my description")) {
                return badRequest("broken form");
            }

            return async(new Callable<Result>() {
                @Override
                public Result call() throws Exception {
                    return ok(item.stream()).as(MimeTypes.BINARY);
                }
            });
        }
    };
    Router router = mock(Router.class);
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);

    ContentEngine contentEngine = getMockContentEngine();

    // Configure the server.
    server = new WisdomVertxServer();
    server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null,
            Collections.<ExceptionMapper>emptyList());
    server.configuration = configuration;
    server.vertx = vertx;
    server.start();

    VertxHttpServerTest.waitForStart(server);

    // Now start bunch of clients
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(NUMBER_OF_CLIENTS);

    int port = server.httpPort();

    for (int i = 1; i < NUMBER_OF_CLIENTS + 1; ++i) // create and start threads
        clients.submit(new Client(startSignal, doneSignal, port, i, 2048));

    startSignal.countDown(); // let all threads proceed
    if (!doneSignal.await(60, TimeUnit.SECONDS)) { // wait for all to finish
        Assert.fail("testFileUploadOfSmallFilesWithAsyncDownload - Client not served in time");
    }
    assertThat(failure).isEmpty();
    assertThat(success).hasSize(NUMBER_OF_CLIENTS);
}

From source file:io.nats.client.ITClusterTest.java

@Test
public void testProperFalloutAfterMaxAttemptsWithAuthMismatch() throws Exception {
    final String[] myServers = { "nats://localhost:1222", "nats://localhost:4443" };

    Options opts = new Options.Builder(defaultOptions()).dontRandomize().maxReconnect(5)
            .reconnectWait(25, TimeUnit.MILLISECONDS).build();
    opts.servers = Nats.processUrlArray(myServers);

    final CountDownLatch dcLatch = new CountDownLatch(1);
    opts.disconnectedCb = new DisconnectedCallback() {
        public void onDisconnect(ConnectionEvent event) {
            dcLatch.countDown();
        }/*from  w ww  . jav a 2  s  .  c  o  m*/
    };

    final AtomicBoolean closedCbCalled = new AtomicBoolean(false);
    final CountDownLatch ccLatch = new CountDownLatch(1);
    opts.closedCb = new ClosedCallback() {
        public void onClose(ConnectionEvent event) {
            closedCbCalled.set(true);
            ccLatch.countDown();
        }
    };

    try (NatsServer s1 = runServerOnPort(1222)) {
        try (NatsServer s2 = runServerWithConfig("tlsverify.conf")) {
            try (ConnectionImpl nc = (ConnectionImpl) opts.connect()) {
                s1.shutdown();

                // wait for disconnect
                assertTrue("Did not receive a disconnect callback message",
                        await(dcLatch, 5, TimeUnit.SECONDS));

                // Wait for ClosedCB
                assertTrue("Did not receive a closed callback message", await(ccLatch, 5, TimeUnit.SECONDS));

                // Make sure we are not still reconnecting.
                assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get());

                // Make sure we have not exceeded MaxReconnect
                assertEquals("Wrong number of reconnects", nc.getOptions().getMaxReconnect(),
                        nc.getStats().getReconnects());

                // Make sure we are not still reconnecting
                assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get());

                // Expect connection to be closed...
                assertTrue("Wrong status: " + nc.getState(), nc.isClosed());
            }
        }
    }
}

From source file:com.microsoft.office.core.MessagesAsyncTestCase.java

private void readAndCheck() throws Exception {
    // reread a message
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getMessages().getAsync(message.getId()), new FutureCallback<IMessage>() {
        @Override//www .ja  v a2s  .  c om
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IMessage result) {
            try {
                MessagesAsyncTestCase.this.message = result;
                Class<?> cls = MessagesAsyncTestCase.this.message.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceMessage.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(property.getPrimitiveValue().toValue(),
                                getter.invoke(MessagesAsyncTestCase.this.message));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

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

private void readAndCheck() throws Exception {
    // reread a message
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getMessages().getAsync(message.getId()), new FutureCallback<IMessage>() {
        public void onFailure(Throwable t) {
            reportError(t);/*from w  w  w . j  a  va 2s  .c  o m*/
            cdl.countDown();
        }

        public void onSuccess(IMessage result) {
            try {
                MessagesAsyncTestCase.this.message = result;
                Class<?> cls = MessagesAsyncTestCase.this.message.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceMessage.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(property.getPrimitiveValue().toValue(),
                                getter.invoke(MessagesAsyncTestCase.this.message));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:interactivespaces.activity.component.ActivityComponentContextTest.java

/**
 * Make a couple of threads start running and see if they properly stop
 * running when the context signals startup successful.
 *///from  w w w  .j  a  v a  2 s.  c  o m
@Test
public void testStartupWaitWithTwoThreadsSuccess() throws Exception {
    final CountDownLatch startLatch = new CountDownLatch(2);
    final CountDownLatch stopLatch = new CountDownLatch(2);
    final AtomicInteger countAllowedHandlers = new AtomicInteger(0);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            startLatch.countDown();

            if (context.canHandlerRun()) {
                countAllowedHandlers.incrementAndGet();
            }

            stopLatch.countDown();
        }
    };

    executor.execute(runnable);
    executor.execute(runnable);

    // Make sure they have both entered before starting the wait.
    Assert.assertTrue(startLatch.await(500, TimeUnit.MILLISECONDS));

    context.endStartupPhase(true);

    // Make sure they have both entered before starting the wait.
    Assert.assertTrue(stopLatch.await(500, TimeUnit.MILLISECONDS));

    // All handlers should have been allowed.
    Assert.assertEquals(2, countAllowedHandlers.get());
}