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.bt.aloha.dialog.DialogConcurrentUpdateBlockTest.java

@Test
public void testSequenceNumberReleasedOnFailedUpdate() {
    // setup/*  w ww  .  java 2s.  c  om*/
    final CountDownLatch firstWriterRead = new CountDownLatch(1);
    final CountDownLatch secondWriterWrote = new CountDownLatch(1);

    DialogConcurrentUpdateBlock dialogConcurrentUpdateBlock = new DialogConcurrentUpdateBlock(
            dialogBeanHelper) {
        public void execute() {
            DialogInfo dialogInfo = dialogCollection.get("id");
            firstWriterRead.countDown();
            assignSequenceNumber(dialogInfo, Request.INVITE);
            log.debug("Waiting for second writer to write");
            try {
                secondWriterWrote.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            dialogCollection.replace(dialogInfo);
        }

        public String getResourceId() {
            return "id";
        }
    };

    // act
    new Thread(new CompetingWriter(firstWriterRead, secondWriterWrote)).start();
    concurrentUpdateManager.executeConcurrentUpdate(dialogConcurrentUpdateBlock);

    // assert
    assertEquals(5, dialogCollection.get("id").getSequenceNumber());
    assertEquals(1, releasedSequenceNumbers.size());
    assertEquals(4, releasedSequenceNumbers.get(0));
    assertEquals(5, lastSequenceNumber);
}

From source file:com.bt.aloha.dialog.DialogConcurrentUpdateBlockTest.java

@Test
public void testSequenceNumberReleasedOnFailedForcedUpdate() {
    // setup/*from   ww w . j a va 2 s  .  c o m*/
    final CountDownLatch firstWriterRead = new CountDownLatch(1);
    final CountDownLatch secondWriterWrote = new CountDownLatch(1);

    DialogConcurrentUpdateBlock dialogConcurrentUpdateBlock = new DialogConcurrentUpdateBlock(
            dialogBeanHelper) {
        public void execute() {
            DialogInfo dialogInfo = dialogCollection.get("id");
            firstWriterRead.countDown();
            forceSequenceNumber(dialogInfo.getId(), 4L, Request.INVITE);
            log.debug("Waiting for second writer to write");
            try {
                secondWriterWrote.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            dialogCollection.replace(dialogInfo);
        }

        public String getResourceId() {
            return "id";
        }
    };

    // act
    new Thread(new CompetingWriter(firstWriterRead, secondWriterWrote)).start();
    concurrentUpdateManager.executeConcurrentUpdate(dialogConcurrentUpdateBlock);

    // assert
    assertEquals(3, dialogCollection.get("id").getSequenceNumber());
    assertEquals(1, releasedSequenceNumbers.size());
    assertEquals(4, releasedSequenceNumbers.get(0));
    assertEquals(4, lastSequenceNumber);
}

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

@Test
public void testGetFlavorAsync() throws IOException, InterruptedException {
    final Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavor1);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.getFlavorAsync(flavor1.getId(), new FutureCallback<Flavor>() {
        @Override/*from w  w  w  .j a  v a 2 s . c  o m*/
        public void onSuccess(@Nullable Flavor result) {
            assertEquals(result, flavor1);
            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 testGetFlavorAsync() throws IOException, InterruptedException {
    final Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavor1);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.getFlavorAsync(flavor1.getId(), new FutureCallback<Flavor>() {
        @Override/*from w  w  w  . j av  a2s.c  om*/
        public void onSuccess(@Nullable Flavor result) {
            assertEquals(result, flavor1);
            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:reactor.ipc.netty.tcp.TcpServerTests.java

@Test
public void exposesNettyPipelineConfiguration() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(2);

    final TcpClient client = TcpClient.create(port);

    BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>> serverHandler = (in,
            out) -> {//from w  w w. j  a v  a  2 s . c o  m
        in.receive().asString().subscribe(data -> {
            log.info("data " + data + " on " + in);
            latch.countDown();
        });
        return Flux.never();
    };

    TcpServer server = TcpServer
            .create(opts -> opts.afterChannelInit(c -> c.pipeline().addBefore(NettyPipeline.ReactiveBridge,
                    "codec", new LineBasedFrameDecoder(8 * 1024))).listen(port));

    NettyContext connected = server.newHandler(serverHandler).block(Duration.ofSeconds(30));

    client.newHandler((in, out) -> out.send(
            Flux.just("Hello World!\n", "Hello 11!\n").map(b -> out.alloc().buffer().writeBytes(b.getBytes()))))
            .block(Duration.ofSeconds(30));

    assertTrue("Latch was counted down", latch.await(10, TimeUnit.SECONDS));

    connected.dispose();
}

From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    final MessageConverter<TBase<?, ?>> messageConverter = new BypassMessageConverter<TBase<?, ?>>();
    final MessageSerializer<ByteMessage> thriftMessageSerializer = new ThriftUdpMessageSerializer(
            messageConverter, ThriftUdpMessageSerializer.UDP_MAX_PACKET_LENGTH) {
        @Override//ww  w  .j  a  v  a2s. c  o  m
        protected boolean isLimit(int interBufferSize) {
            final boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };

    UdpDataSender sender = new UdpDataSender("localhost", PORT, "test", 128, 1000, 1024 * 64 * 100,
            thriftMessageSerializer);
    try {
        sender.send(tbase);
        latch.await(waitTimeMillis, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

From source file:com.palantir.docker.compose.logging.FileLogCollectorShould.java

@Test
public void collect_logs_when_one_container_is_running_and_does_not_terminate_until_after_start_collecting_is_run()
        throws Exception {
    when(compose.ps()).thenReturn(TestContainerNames.of("db"));
    CountDownLatch latch = new CountDownLatch(1);
    when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> {
        if (!latch.await(1, TimeUnit.SECONDS)) {
            throw new RuntimeException("Latch was not triggered");
        }//from ww w  .j ava 2  s  .  c  o m
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("log", outputStream);
        return false;
    });
    logCollector.startCollecting(compose);
    latch.countDown();
    logCollector.stopCollecting();
    assertThat(logDirectory.listFiles(), arrayContaining(fileWithName("db.log")));
    assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log")));
}

From source file:com.twitter.distributedlog.auditor.DLAuditor.java

static <T> void executeAction(final LinkedBlockingQueue<T> queue, final int numThreads, final Action<T> action)
        throws IOException {
    final CountDownLatch failureLatch = new CountDownLatch(1);
    final CountDownLatch doneLatch = new CountDownLatch(queue.size());
    final AtomicInteger numFailures = new AtomicInteger(0);
    final AtomicInteger completedThreads = new AtomicInteger(0);

    ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
    try {/*from w ww  .  j  av a2  s.  com*/
        for (int i = 0; i < numThreads; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        T item = queue.poll();
                        if (null == item) {
                            break;
                        }
                        try {
                            action.execute(item);
                        } catch (IOException ioe) {
                            logger.error("Failed to execute action on item '{}'", item, ioe);
                            numFailures.incrementAndGet();
                            failureLatch.countDown();
                            break;
                        }
                        doneLatch.countDown();
                    }
                    if (numFailures.get() == 0 && completedThreads.incrementAndGet() == numThreads) {
                        failureLatch.countDown();
                    }
                }
            });
        }
        try {
            failureLatch.await();
            if (numFailures.get() > 0) {
                throw new IOException("Encountered " + numFailures.get() + " failures on executing action.");
            }
            doneLatch.await();
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            logger.warn("Interrupted on executing action", ie);
            throw new DLInterruptedException("Interrupted on executing action", ie);
        }
    } finally {
        executorService.shutdown();
    }
}

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

@Test
public void testCreateAsync() throws Exception {
    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.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override// w  w  w  .  ja  v  a2  s  . co 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 testCreateAsync() throws Exception {
    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.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override//from   ww  w .j a va  2 s  . co  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));
}