Example usage for java.util.concurrent CountDownLatch CountDownLatch

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

Introduction

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

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

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

@Test
public void testCustomExecutor() throws Exception {
    final int ITERATIONS = 1000;

    Timing timing = new Timing();
    DistributedQueue<String> queue = null;
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();/*from  w  w w. j  a  va  2  s .c o  m*/
    try {
        final CountDownLatch latch = new CountDownLatch(ITERATIONS);
        QueueConsumer<String> consumer = new QueueConsumer<String>() {
            @Override
            public void consumeMessage(String message) throws Exception {
                latch.countDown();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        QueueSerializer<String> serializer = new QueueSerializer<String>() {
            @Override
            public byte[] serialize(String item) {
                return item.getBytes();
            }

            @Override
            public String deserialize(byte[] bytes) {
                return new String(bytes);
            }
        };

        Executor executor = Executors.newCachedThreadPool();

        final Set<String> used = Sets.newHashSet();
        final Set<String> doubleUsed = Sets.newHashSet();
        queue = new DistributedQueue<String>(client, consumer, serializer, QUEUE_PATH,
                QueueBuilder.defaultThreadFactory, executor, Integer.MAX_VALUE, false, "/lock",
                QueueBuilder.NOT_SET, true, 5000) {
            @SuppressWarnings("SimplifiableConditionalExpression")
            @Override
            protected boolean processWithLockSafety(String itemNode, DistributedQueue.ProcessType type)
                    throws Exception {
                if (used.contains(itemNode)) {
                    doubleUsed.add(itemNode);
                } else {
                    used.add(itemNode);
                }
                return (client.getState() == CuratorFrameworkState.STARTED)
                        ? super.processWithLockSafety(itemNode, type)
                        : false;
            }
        };
        queue.start();

        for (int i = 0; i < ITERATIONS; ++i) {
            queue.put(Integer.toString(i));
        }

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

        Assert.assertTrue(doubleUsed.size() == 0, doubleUsed.toString());
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.vmware.photon.controller.nsxclient.apis.DhcpServiceApiTest.java

@Test
public void testGetDhcpRelayProfile() throws IOException, InterruptedException {
    final DhcpRelayProfile mockResponse = new DhcpRelayProfile();
    mockResponse.setId("id");
    mockResponse.setResourceType(ServiceProfileResourceType.DHCP_RELAY_PROFILE);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getDhcpRelayProfile("id", new com.google.common.util.concurrent.FutureCallback<DhcpRelayProfile>() {
        @Override/*w w w  . ja va2s .  c  om*/
        public void onSuccess(DhcpRelayProfile result) {
            assertEquals(result, mockResponse);
            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.ottogroup.bi.streaming.runtime.StreamingAppRuntimeTest.java

/**
 * Test case for {@link StreamingAppRuntime#getOptions()}
 *//*from www .  j  ava  2s .  c o  m*/
@Test
public void testGetOptions() {
    final Options options = new DummyLogProcessingRuntime(new CountDownLatch(1)).getOptions();
    Assert.assertNotNull(options);
    Assert.assertFalse(options.getOptions().isEmpty());
    Assert.assertEquals(1, options.getOptions().size());
    Assert.assertTrue(options.hasOption(StreamingAppRuntime.CLI_CONFIG_FILE));
    Assert.assertTrue(options.hasOption(StreamingAppRuntime.CLI_CONFIG_FILE_SHORT));
}

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

@Test(timeout = 60000)
public void deleteTest() throws Exception {
    prepareFolder();//from  w  w  w. jav a2  s  . c  om
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                deleteAndCheck();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });
    counter.await();
}

From source file:com.couchbase.client.TestingClient.java

public HttpFuture<String> asyncHttpGet(String uri) throws UnsupportedEncodingException {
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout);

    HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);
    HttpOperationImpl op = new TestOperationImpl(request, new TestCallback() {
        private String json;

        @Override//from  www .j a va 2 s. c o  m
        public void receivedStatus(OperationStatus status) {
            crv.set(json, status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }

        @Override
        public void getData(String response) {
            json = response;
        }
    });
    crv.setOperation(op);
    addOp(op);
    return crv;
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderLatch.java

@Test
public void testLostConnection() throws Exception {
    final int PARTICIPANT_QTY = 10;

    List<LeaderLatch> latches = Lists.newArrayList();

    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    try {/*  w w  w  .  j  ava 2 s  .  co m*/
        client.start();

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

        for (int i = 0; i < PARTICIPANT_QTY; ++i) {
            LeaderLatch latch = new LeaderLatch(client, PATH_NAME);
            latch.start();
            latches.add(latch);
        }

        waitForALeader(latches, timing);

        server.stop();
        Assert.assertTrue(timing.awaitLatch(countDownLatch));

        timing.forWaiting().sleepABit();

        Assert.assertEquals(getLeaders(latches).size(), 0);

        server = new TestingServer(server.getPort(), server.getTempDirectory());
        Assert.assertEquals(waitForALeader(latches, timing).size(), 1); // should reconnect
    } finally {
        for (LeaderLatch latch : latches) {
            IOUtils.closeQuietly(latch);
        }
        IOUtils.closeQuietly(client);
    }
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Test
public void testCallbackIsInvokedWhenRelevantFileIsDiscovered() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final File[] fileAccessor = new File[1];
    final File tempWriteReplayFolder = new File(directories.getRemainder(), "TempWriteReplayP99");
    final File target = new File(tempWriteReplayFolder, BattleLobbyWatcher.REPLAY_SERVER_BATTLELOBBY);
    tempWatcher.setCallback(file -> {
        fileAccessor[0] = file;/*from   w w  w  .  j  av  a  2  s  . c  om*/
        latch.countDown();
    });

    if (!(tempWriteReplayFolder.mkdirs() && target.createNewFile())) {
        fail("Could not create file to drop target " + target + " in");
    }

    if (!latch.await(50000, TimeUnit.MILLISECONDS)) {
        fail("Latch was not tripped.");
    }

    final String expected = target.getName();
    final String actual = fileAccessor[0].getName();

    assertEquals(expected, actual);
}

From source file:org.apache.felix.http.itest.SessionHandlingTest.java

private void setupLatches(int count) {
    initLatch = new CountDownLatch(count);
    destroyLatch = new CountDownLatch(count);
}

From source file:org.elasticsearch.logstash.Application.java

@Bean
public CountDownLatch latch(Integer numberOfJokes) {
    return new CountDownLatch(numberOfJokes);
}

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

@Test
public void testGetImageAsync() throws IOException, InterruptedException {
    final Image image = new Image();
    image.setId("image1");

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ImagesApi imagesApi = new ImagesApi(this.restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    imagesApi.getImageAsync(image.getId(), new FutureCallback<Image>() {
        @Override//ww  w  . ja v  a  2 s .co m
        public void onSuccess(@Nullable Image result) {
            assertEquals(result, image);
            latch.countDown();
        }

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

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