Example usage for java.util.concurrent CountDownLatch getCount

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

Introduction

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

Prototype

public long getCount() 

Source Link

Document

Returns the current count.

Usage

From source file:org.commonjava.util.partyline.UtilThreads.java

public static Runnable deleter(JoinableFileManager manager, File f, CountDownLatch masterLatch,
        CountDownLatch deleteEndLatch) {
    return () -> {
        Thread.currentThread().setName("delete");
        System.out.println("Starting: " + Thread.currentThread().getName());
        try {// w  w  w . j a va 2  s  . c  om
            manager.tryDelete(f);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (deleteEndLatch != null) {
                System.out.println("Counting down delete latch");
                deleteEndLatch.countDown();
            }
            System.out.println("Counting down master latch");
            masterLatch.countDown();
            System.out.println(String.format("[%s] Count down after delete thread: %s",
                    Thread.currentThread().getName(), masterLatch.getCount()));
        }
    };
}

From source file:org.commonjava.util.partyline.UtilThreads.java

public static Runnable writer(JoinableFileManager manager, File f, CountDownLatch masterLatch,
        CountDownLatch readEndLatch) {
    return () -> {
        Thread.currentThread().setName("openOutputStream");
        System.out.println("Starting: " + Thread.currentThread().getName());

        if (readEndLatch != null) {
            try {
                System.out.println("awaiting read-end latch");
                readEndLatch.await();/* w  ww .  j a v  a  2s. com*/
            } catch (InterruptedException e) {
                return;
            }
        }

        try (OutputStream o = manager.openOutputStream(f)) {
            o.write("Test data".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Counting down master latch");
        masterLatch.countDown();
        System.out.println(String.format("[%s] Count down after write thread: %s",
                Thread.currentThread().getName(), masterLatch.getCount()));
    };
}

From source file:org.seasar.dbflute.helper.thread.CountDownRaceLatch.java

protected long actuallyGetCount(CountDownLatch latch) {
    return latch.getCount();
}

From source file:org.smartfrog.services.anubis.Node.java

public boolean isMissingMessages() {
    for (CountDownLatch latch : msgReceivedLatches.values()) {
        if (latch.getCount() > 0) {
            return true;
        }/*from   w  w w .ja  v a 2s. c o m*/
    }
    return false;
}

From source file:fr.keemto.scheduling.ScheduledTaskIT.java

@Test
public void shouldExecuteFetcherAsychronouslyWithDelay() throws Exception {

    CountDownLatch latch = new CountDownLatch(10);
    Task countDownTask = new CountDownTask(latch);

    scheduler.scheduleTask(countDownTask);
    latch.await(2000, TimeUnit.MILLISECONDS);

    assertThat(latch.getCount(), equalTo((long) 0));
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToPlainPipelineOutputs() throws InterruptedException, JSONException {
    firstStep = newPipelineWithResponseBody("{id:123}");

    // use a synchronized set to collect the pipeline output from multiple threads
    Set<JsonPipelineOutput> distinctOutputs = Collections.synchronizedSet(new HashSet<JsonPipelineOutput>());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    ExecutorService executorService = Executors.newCachedThreadPool();
    CountDownLatch countDown = new CountDownLatch(100);
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();//from   w w w .  j av a 2  s  .  c  o m
            distinctOutputs.add(firstStep.getOutput().toBlocking().single());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    // ensure all threads received the same JsonPipelineOutput instance with the expected JSON output
    assertEquals(1, distinctOutputs.size());
    JSONAssert.assertEquals("{id: 123}", firstStep.getStringOutput().toBlocking().first(),
            JSONCompareMode.STRICT);
}

From source file:com.watchrabbit.executor.spring.AnnotationDiscoverTest.java

@Test
public void shouldCloseCircuit() throws Exception {
    try {/*  w  w w .  j a v  a2 s  .c o m*/
        annotatedService.fastClose(() -> {
            throw new Exception();
        });
        failBecauseExceptionWasNotThrown(Exception.class);
    } catch (Exception ex) {
    }
    Sleep.untilTrue(Boolean.TRUE::booleanValue, 10, TimeUnit.MILLISECONDS);

    CountDownLatch latch = new CountDownLatch(1);
    annotatedService.fastClose(() -> {
        latch.countDown();
        return "ok";
    });
    assertThat(latch.getCount()).isEqualTo(0);
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToTransformedPipelineOutputs() throws InterruptedException {

    // this test verifies that pipelines actions are only executed once, even if there are multiple concurrent subscribers
    firstStep = newPipelineWithResponseBody("{id:123}");
    secondStep = firstStep.applyAction(action);
    when(action.execute(any(), any())).thenReturn(firstStep.getOutput());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    CountDownLatch countDown = new CountDownLatch(100);
    ExecutorService executorService = Executors.newCachedThreadPool();
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();//from w ww. j  a v  a  2s  .  c  o m
            secondStep.getOutput().subscribe(Subscribers.empty());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    verify(action, times(1)).execute(any(), any());
}

From source file:org.usergrid.benchmark.commands.queue.DirectReader.java

@Override
protected void doWork(CommandLine line, Queue<TestEvent> queue, String hostName, int workers, int count)
        throws Exception {

    CountDownLatch latch = new CountDownLatch(count * workers);

    //     queue.observe(new EventListener(latch, readsTimer, readLogger, queue));

    EventListener listener = new EventListener(latch, readsTimer, readLogger, queue);

    IQueue<TestEvent> hzQueue = instance.getQueue(line.getOptionValue("queue"));

    while (latch.getCount() != 0) {

        listener.onMessage(hzQueue.take());
    }//from  ww w  .j  a va2s  .c  o m

    latch.await();

    writeTimerData(readsTimer);

}

From source file:forge.CardStorageReader.java

private List<Callable<List<CardRules>>> makeTaskListForZip(final List<ZipEntry> entries,
        final CountDownLatch cdl) {
    final int totalFiles = entries.size();
    final int maxParts = (int) cdl.getCount();
    final int filesPerPart = totalFiles / maxParts;
    final List<Callable<List<CardRules>>> tasks = new ArrayList<>();
    for (int iPart = 0; iPart < maxParts; iPart++) {
        final int from = iPart * filesPerPart;
        final int till = iPart == maxParts - 1 ? totalFiles : from + filesPerPart;
        tasks.add(new Callable<List<CardRules>>() {
            @Override//from   w w w .java  2  s.  co m
            public List<CardRules> call() throws Exception {
                final List<CardRules> res = loadCardsInRangeFromZip(entries, from, till);
                cdl.countDown();
                progressObserver.report(maxParts - (int) cdl.getCount(), maxParts);
                return res;
            }
        });
    }
    return tasks;
}