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.vmware.photon.controller.api.client.resource.DisksRestApiTest.java

@Test
public void testGetDiskAsync() throws IOException, InterruptedException {
    final PersistentDisk persistentDisk = new PersistentDisk();
    persistentDisk.setId("persistentDisk");

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    DisksApi disksApi = new DisksRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    disksApi.getDiskAsync("disk1", new FutureCallback<PersistentDisk>() {
        @Override//w w w. j  a v  a2  s.c  om
        public void onSuccess(@Nullable PersistentDisk result) {
            assertEquals(result, persistentDisk);
            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.nsxclient.apis.FabricApiTest.java

@Test
public void testDeleteTransportNode() throws IOException, InterruptedException {
    setupMocks(null, HttpStatus.SC_OK);//from ww w  .jav  a2s .  c o m

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.deleteTransportNode("id", new com.google.common.util.concurrent.FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            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.nsxclient.apis.FabricApiTest.java

@Test
public void testDeleteTransportZone() throws IOException, InterruptedException {
    setupMocks(null, HttpStatus.SC_OK);//  w  ww  .  j  a v  a 2s  .c  om

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.deleteTransportZone("id", new com.google.common.util.concurrent.FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            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.dangdang.ddframe.job.api.type.dataflow.executor.DataflowJobExecutor.java

private void processDataForThroughput(final int concurrentDataProcessThreadCount,
        final ShardingContext shardingContext, final List<Object> data) {
    if (concurrentDataProcessThreadCount <= 1 || data.size() <= concurrentDataProcessThreadCount) {
        processData(shardingContext, data);
        return;//ww w  .j a  va  2s  . com
    }
    List<List<Object>> splitData = Lists.partition(data, data.size() / concurrentDataProcessThreadCount);
    final CountDownLatch latch = new CountDownLatch(splitData.size());
    for (final List<Object> each : splitData) {
        getExecutorService().submit(new Runnable() {

            @Override
            public void run() {
                try {
                    processData(shardingContext, each);
                } finally {
                    latch.countDown();
                }
            }
        });
    }
    latchAwait(latch);
}

From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java

/**
 * postThread posts a top comment to Elastic-Search.
 * Tested and verified./* w  w w.  j  a  va 2s. c  o m*/
 * @param ElasticSearchOperations
 * @throws InterruptedException 
 */
public static void postThread(final Comment commentThread) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    if (GSON == null)
        constructGson();

    Thread thread = new Thread() {

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(postAddress + commentThread.getUuid() + "/");

            try {
                request.setEntity(new StringEntity(GSON.toJson(commentThread)));

                HttpResponse response = client.execute(request);
                Log.w(serverName, response.getStatusLine().toString());

                response.getStatusLine().toString();
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String output = reader.readLine();
                while (output != null) {
                    Log.w(serverName, output);
                    output = reader.readLine();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    };
    thread.start();
    latch.await();
}

From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java

/**
 * Pushes the UserProfileModel onto the server
 * @param uPModel//from   w ww.  j  av  a 2  s. c om
 * @throws InterruptedException
 */
public static void pushUserProfile(final UserProfileModel uPModel) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    if (GSON == null)
        constructGson();

    Thread thread = new Thread() {

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(profileAddress + uPModel.getUniqueID() + "/");

            try {

                request.setEntity(new StringEntity(GSON.toJson(uPModel)));

                HttpResponse response = client.execute(request);
                Log.w(serverName, response.getStatusLine().toString());

                response.getStatusLine().toString();
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String output = reader.readLine();
                while (output != null) {
                    Log.w(serverName, output);
                    output = reader.readLine();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    };
    thread.start();
    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:org.cleverbus.core.common.asynch.queue.MessagePollExecutorTest.java

@Test
public void testGetNextMessage_moreThreads() throws InterruptedException {
    // prepare threads
    int threads = 5;
    final CountDownLatch latch = new CountDownLatch(threads);
    Runnable task = new Runnable() {

        @Override//from  w w w .ja  v  a2  s .  c o  m
        public void run() {
            try {
                messagePollExecutor.run();
            } finally {
                latch.countDown();
            }
        }
    };

    mock.expectedMessageCount(3);

    // start processing and waits for result
    for (int i = 0; i < threads; i++) {
        new Thread(task).start();
    }

    latch.await();

    mock.assertIsSatisfied();

    // verify messages
    Message msg = findMessage("1234_4567");
    assertThat(msg, notNullValue());
    assertThat(msg.getState(), is(MsgStateEnum.PROCESSING));

    msg = findMessage("1234_4567_8");
    assertThat(msg, notNullValue());
    assertThat(msg.getState(), is(MsgStateEnum.PROCESSING));

    msg = findMessage("1234_4567_9");
    assertThat(msg, notNullValue());
    assertThat(msg.getState(), is(MsgStateEnum.PROCESSING));
}

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

@Test
public void testUnregisterFabricNode() throws IOException, InterruptedException {
    setupMocks(null, HttpStatus.SC_OK);//from  w w w . j a  v a2  s .c  o m

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.unregisterFabricNode("nodeId", new com.google.common.util.concurrent.FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            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.asakusafw.runtime.util.cache.HadoopFileCacheRepositoryTest.java

/**
 * Conflict cache creation./*from  w  w  w  .ja  v a 2  s  .com*/
 * @throws Exception if failed
 */
@Test
public void conflict() throws Exception {
    File source = folder.newFile();
    byte[] bytes = new byte[1024 * 1024];
    try (OutputStream output = new FileOutputStream(source)) {
        for (int i = 0, n = 50; i < n; i++) {
            output.write(bytes);
        }
    }

    Path path = path(source);
    File cacheRepo = folder.newFolder();
    Configuration configuration = new ConfigurationProvider().newInstance();
    LockProvider<Path> locks = new LocalFileLockProvider<>(folder.newFolder());
    RetryStrategy retrier = new ConstantRetryStrategy(30, 100, 200);
    FileCacheRepository cache = new HadoopFileCacheRepository(configuration, path(cacheRepo), locks, retrier);

    List<Future<Path>> futures = new ArrayList<>();
    int count = 10;
    CountDownLatch latch = new CountDownLatch(count);
    ExecutorService executor = Executors.newFixedThreadPool(count);
    try {
        for (int i = 0; i < count; i++) {
            String label = String.format("thread-%d", i);
            futures.add(executor.submit(() -> {
                LOG.info("Wait: resolve @" + label);
                latch.countDown();
                if (latch.await(5, TimeUnit.SECONDS) == false) {
                    throw new TimeoutException();
                }
                LOG.info("Start: resolve @" + label);
                Path result = cache.resolve(path);

                LOG.info("Finish: resolve @" + label);
                return result;
            }));
        }
        executor.shutdown();
        if (executor.awaitTermination(30, TimeUnit.SECONDS) == false) {
            throw new TimeoutException();
        }
    } finally {
        executor.shutdownNow();
    }
    for (Future<Path> future : futures) {
        future.get();
    }
}

From source file:com.contentful.vaultintegration.BaseTest.java

protected void sync(SyncConfig config) throws InterruptedException {
    if (config == null) {
        config = SyncConfig.builder().setClient(client).build();
    }//  w  ww .  j av  a2  s .  co m

    final CountDownLatch latch = new CountDownLatch(1);

    Executor executor = new Executor() {
        @Override
        public void execute(Runnable command) {
            command.run();
        }
    };

    final SyncResult[] result = { null };
    SyncCallback callback = new SyncCallback() {
        @Override
        public void onResult(SyncResult r) {
            result[0] = r;
            latch.countDown();
        }
    };

    vault.requestSync(config, callback, executor);
    latch.await();

    assertThat(result[0]).isNotNull();

    if (!result[0].isSuccessful()) {
        throw (RuntimeException) result[0].error();
    }
}