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:org.eclipse.hono.application.HonoApplication.java

/**
 * Stops the Hono server in a controlled fashion.
 * /*from   ww  w.j  av a2  s  .  c  om*/
 * @param maxWaitTime The maximum time to wait for the server to shut down (in seconds).
 * @param shutdownHandler The handler to invoke with the result of the shutdown attempt.
 */
public final void shutdown(final long maxWaitTime, final Handler<Boolean> shutdownHandler) {

    try {
        preShutdown();
        final CountDownLatch latch = new CountDownLatch(1);
        if (vertx != null) {
            LOG.debug("shutting down Hono server...");
            vertx.close(r -> {
                if (r.failed()) {
                    LOG.error("could not shut down Hono cleanly", r.cause());
                }
                latch.countDown();
            });
        }
        if (latch.await(maxWaitTime, TimeUnit.SECONDS)) {
            LOG.info("Hono server has been shut down successfully");
            shutdownHandler.handle(Boolean.TRUE);
        } else {
            LOG.error("shut down of Hono server timed out, aborting...");
            shutdownHandler.handle(Boolean.FALSE);
        }
    } catch (InterruptedException e) {
        LOG.error("shut down of Hono server has been interrupted, aborting...");
        Thread.currentThread().interrupt();
        shutdownHandler.handle(Boolean.FALSE);
    }
}

From source file:com.uber.tchannel.ping.PingClient.java

public void run() throws Exception {
    TChannel tchannel = new TChannel.Builder("ping-client").build();
    SubChannel subChannel = tchannel.makeSubChannel("ping-server");
    final ConcurrentHashMap<String, Integer> msgs = new ConcurrentHashMap<String, Integer>();
    final CountDownLatch done = new CountDownLatch(requests);

    for (int i = 0; i < requests; i++) {
        JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
                .setBody(new Ping("{'key': 'ping?'}")).setHeader("some", "header").setTimeout(100 + i).build();
        TFuture<JsonResponse<Pong>> f = subChannel.send(request, InetAddress.getByName(host), port);

        f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
            @Override/*from   w  ww . j  av a 2  s  .com*/
            public void onResponse(JsonResponse<Pong> pongResponse) {
                done.countDown();
                String msg = pongResponse.toString();
                if (msgs.containsKey(msg)) {
                    msgs.put(msg, msgs.get(msg) + 1);
                } else {
                    msgs.put(msg, 1);
                }
            }
        });
    }

    done.await();
    for (String msg : msgs.keySet()) {
        System.out.println(String.format("%s\n\tcount:%d", msg, msgs.get(msg)));
    }

    tchannel.shutdown(false);
}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedPriorityQueue.java

@Test
public void testSimple() throws Exception {
    List<Integer> nums = new ArrayList<Integer>();

    Timing timing = new Timing();
    DistributedPriorityQueue<Integer> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();// www  .  j a v a2s . com
    try {
        final CountDownLatch hasConsumedLatch = new CountDownLatch(1);
        final CountDownLatch okToConsumeLatch = new CountDownLatch(1);
        BlockingQueueConsumer<Integer> consumer = new BlockingQueueConsumer<Integer>(
                Mockito.mock(ConnectionStateListener.class)) {
            @Override
            public void consumeMessage(Integer message) throws Exception {
                hasConsumedLatch.countDown();
                okToConsumeLatch.await();
                super.consumeMessage(message);
            }
        };
        queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0);
        queue.start();

        nums.add(Integer.MIN_VALUE);
        queue.put(Integer.MIN_VALUE, Integer.MIN_VALUE); // the queue background thread will be blocking with the first item - make sure it's the lowest value
        Assert.assertTrue(timing.awaitLatch(hasConsumedLatch));

        Random random = new Random();
        for (int i = 0; i < 100; ++i) {
            int priority = random.nextInt();
            nums.add(priority);
            queue.put(priority, priority);
        }

        while (queue.getCache().getData().children.size() < (nums.size() - 1)) // -1 because the first message has already been consumed
        {
            timing.sleepABit(); // wait for the cache to catch up
        }
        okToConsumeLatch.countDown();

        assertOrdering(consumer, nums.size());
    } catch (AssertionError e) {
        StringBuilder message = new StringBuilder(e.getMessage());
        for (int i : nums) {
            message.append(i).append("\t").append(DistributedPriorityQueue.priorityToString(i)).append("\n");
        }
        Assert.fail(message.toString());
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

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

@Test
public void testReconnectAfterLoss() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {//from w w w  .j  a  v a 2  s.  c om
        client.start();

        final CountDownLatch lostLatch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    lostLatch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);

        client.checkExists().forPath("/");

        server.close();

        Assert.assertTrue(timing.awaitLatch(lostLatch));

        try {
            client.checkExists().forPath("/");
            Assert.fail();
        } catch (KeeperException.ConnectionLossException e) {
            // correct
        }

        server = new TestingServer(server.getPort());
        client.checkExists().forPath("/");
    } finally {
        IOUtils.closeQuietly(client);
    }
}

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

@Test
public void testBackgroundFailure() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();// ww w  .j  a v  a 2  s . c o m
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        });

        client.checkExists().forPath("/hey");
        client.checkExists().inBackground().forPath("/hey");

        server.stop();

        client.checkExists().inBackground().forPath("/hey");
        Assert.assertTrue(timing.awaitLatch(latch));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

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

private Thread setupShutdownHook(final Injector primary, final CountDownLatch shutdown) {
    final Thread thread = new Thread() {
        @Override/*  ww w . j  a va 2s.  c o m*/
        public void run() {
            try {
                AgentCore.this.stop(primary);
            } catch (Exception e) {
                log.error("AgentCore#stop(Injector) failed", e);
            }

            shutdown.countDown();
        }
    };

    thread.setName("ffwd-agent-core-shutdown-hook");

    return thread;
}

From source file:com.vmware.photon.controller.api.client.resource.FlavorApiTest.java

@Test
public void testDeleteAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//  w w  w  . j a  v  a2 s. c o  m
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.api.client.resource.FlavorRestApiTest.java

@Test
public void testDeleteAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    FlavorApi flavorApi = new FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//from w  w w. j av  a 2s.c o  m
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:io.kodokojo.bdd.stage.HttpUserSupport.java

public WebSocketConnectionResult connectToWebSocketAndWaitMessage(UserInfo user,
        CountDownLatch nbMessageExpected) {

    CountDownLatch webSocketConnected = new CountDownLatch(1);
    WebSocketEventsListener.CallBack delegate = new WebSocketEventsListener.CallBack() {
        @Override//from   w  w  w  .j av a2s  .c o  m
        public void open(Session session) {
            webSocketConnected.countDown();
        }

        @Override
        public void receive(Session session, String message) {
            nbMessageExpected.countDown();
        }

        @Override
        public void close(Session session) {
            webSocketConnected.countDown();
        }
    };

    WebSocketEventsListener listener = new WebSocketEventsListener(
            new WebSocketEventsCallbackWrapper(delegate, user));
    Session session = connectToWebSocketEvent(user, listener);

    try {
        webSocketConnected.await(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        //  NOTHING TO DO
    }

    return new WebSocketConnectionResult(session, listener);
}

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  ww w .  ja va 2s  . c  om*/
            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");
}