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:forge.CardStorageReader.java

private List<Callable<List<CardRules>>> makeTaskListForFiles(final List<File> allFiles,
        final CountDownLatch cdl) {
    final int totalFiles = allFiles.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 ww .  j  ava 2s .c  o m
            public List<CardRules> call() throws Exception {
                final List<CardRules> res = loadCardsInRange(allFiles, from, till);
                cdl.countDown();
                progressObserver.report(maxParts - (int) cdl.getCount(), maxParts);
                return res;
            }
        });
    }
    return tasks;
}

From source file:org.eclipse.gyrex.http.jetty.internal.JettyEngineApplication.java

boolean isActive() {
    final CountDownLatch stopSignal = stopSignalRef.get();
    return (stopSignal != null) && (stopSignal.getCount() > 0);
}

From source file:org.archive.modules.seeds.TextSeedModule.java

/**
 * Announce all seeds from configured source to SeedListeners 
 * (including nonseed lines mixed in). /*w w  w .  j a  v  a 2s  . co m*/
 * @see org.archive.modules.seeds.SeedModule#announceSeeds()
 */
public void announceSeeds() {
    if (getBlockAwaitingSeedLines() > -1) {
        final CountDownLatch latch = new CountDownLatch(getBlockAwaitingSeedLines());
        new Thread() {
            @Override
            public void run() {
                announceSeeds(latch);
                while (latch.getCount() > 0) {
                    latch.countDown();
                }
            }
        }.start();
        try {
            latch.await();
        } catch (InterruptedException e) {
            // do nothing
        }
    } else {
        announceSeeds(null);
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSCxfContinuationsTest.java

private void doTestContinuation(String pathSegment) throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);

    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/1", "1",
            "CXF in Action1", startSignal, doneSignal));
    startSignal.countDown();//from w  ww. j a va2 s  .c  o m
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
}

From source file:org.pentaho.di.core.hadoop.HadoopConfigurationBootstrap.java

public HadoopConfigurationProvider getProvider() throws ConfigurationException {
    try {//from w w w.ja  va 2s  .  co  m
        int timeout = NumberUtils
                .toInt(getMergedPmrAndPluginProperties().getProperty(MAX_TIMEOUT_BEFORE_LOADING_SHIM), 300);
        CountDownLatch remainingDependencies = getRemainingDependencies();
        long nrNotifications = remainingDependencies.getCount();
        if (nrNotifications > 0) {
            log.logDebug(BaseMessages.getString(PKG, "HadoopConfigurationBootstrap.WaitForShimLoad",
                    nrNotifications, timeout));
        }
        remainingDependencies.await(timeout, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // Make sure wait happens on first load only
        while (remainingDependencies.getCount() > 0) {
            remainingDependencies.countDown();
        }

        Thread.currentThread().interrupt();
    }

    initProvider();
    return provider;
}

From source file:org.commonjava.cartographer.INTERNAL.ops.ResolveOpsImpl.java

private List<RepoContentCollector> collectContent(final Map<ProjectVersionRef, ProjectRefCollection> refMap,
        final RepositoryContentRequest recipe) throws CartoDataException, CartoRequestException {
    final Location location = recipe.getSourceLocation();
    final Set<Location> excluded = recipe.getExcludedSourceLocations();

    if (excluded != null && excluded.contains(location)) {
        // no sense in going through all the rest if everything is excluded...
        throw new CartoDataException(
                "RepositoryContentRequest is insane! Source location is among those excluded!");
    }/*from  w w w .  j a  v  a  2  s.c  om*/

    int projectCounter = 1;
    final int projectSz = refMap.size();
    final List<RepoContentCollector> collectors = new ArrayList<>(projectSz);

    final DiscoveryConfig dconf = recipe.getDiscoveryConfig();

    for (final Map.Entry<ProjectVersionRef, ProjectRefCollection> entry : refMap.entrySet()) {
        final ProjectVersionRef ref = entry.getKey();
        final ProjectRefCollection refs = entry.getValue();

        final RepoContentCollector collector = new RepoContentCollector(ref, refs, recipe, location, dconf,
                artifacts, discoverer, excluded, projectCounter, projectSz);

        collectors.add(collector);

        projectCounter++;
    }

    final CountDownLatch latch = new CountDownLatch(collectors.size());
    for (final RepoContentCollector collector : collectors) {
        collector.setLatch(latch);
        executor.execute(collector);
    }

    // TODO: timeout with loop...
    while (latch.getCount() > 0) {
        logger.info("Waiting for {} more content-collection threads to complete.", latch.getCount());
        try {
            latch.await(2, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            logger.error("Abandoning repo-content assembly for: {}", recipe);
        }
    }

    return collectors;
}

From source file:io.fabric8.msg.jnatsd.TestNullPayload.java

@Test
public void testNullPayload() throws Exception {
    Connection connection = connectionFactory.createConnection();
    final int count = 100;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    Subscription subscription = connection.subscribe("foo", new MessageHandler() {
        @Override/*from   w w w.  ja v  a 2 s.  c o  m*/
        public void onMessage(Message message) {
            countDownLatch.countDown();
        }
    });

    for (int i = 0; i < count; i++) {
        connection.publish("foo", null);
    }

    countDownLatch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(0, countDownLatch.getCount());
    connection.close();
}

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

@Test
public void shouldNotClose() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    try {/*w  ww .  j  ava2 s  . c om*/
        annotatedService.excludedSystemException(() -> {
            throw new SystemException();
        });
        failBecauseExceptionWasNotThrown(SystemException.class);
    } catch (SystemException ex) {
    }
    annotatedService.excludedSystemException(() -> {
        latch.countDown();
        return null;
    });

    assertThat(latch.getCount()).isEqualTo(0);
}

From source file:com.android.switchaccess.SwitchAccessEndToEndTest.java

@MediumTest
public void testButton1_click() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return;//  w w  w  .  j  a  va2s  .c  o  m
    }

    final Button button = (Button) getActivity().findViewById(R.id.button_1);
    final CountDownLatch clicksMissed = new CountDownLatch(1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clicksMissed.countDown();
        }
    });
    sendKeyEventSync(mMoveFocusEvent);
    sendKeyEventSync(mMoveFocusKeyUpEvent);
    sendKeyEventSync(mMoveFocusEvent);
    sendKeyEventSync(mClickEvent);
    assertEquals(0, clicksMissed.getCount());
}

From source file:org.bpmscript.correlation.hibernate.HibernateCorrelationServiceTest.java

/**
 * Test method for {@link org.bpmscript.correlation.hibernate.HibernateCorrelationService#send(java.lang.Object)}.
 * @throws Exception //from w ww .ja v  a  2 s.  c o m
 */
public void testXml() throws Exception {
    final int total = 1;
    final int criteriaTotal = 1;
    final CountDownLatch latch = new CountDownLatch(total);
    //final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    HibernateCorrelationServiceTestSupport testSupport = new HibernateCorrelationServiceTestSupport(
            new ICorrelationChannel() {

                public void send(Serializable replyToken, Object message) {
                    assertEquals("replyToken", replyToken);
                    log.info(latch.getCount());
                    latch.countDown();
                }

                public Object getContent(Object message) {
                    return null;
                }

            });
    testSupport.execute(new ITestCallback<IServiceLookup>() {
        public void execute(IServiceLookup services) throws Exception {
            final HibernateCorrelationService correlationService = services.get("correlationService");
            {
                Correlation correlation = new Correlation();
                correlation.addCriteria("new XML(message).text().toString()", "Hello World!");
                correlationService.addCorrelation("channel", "groupId", "correlationId", "replyToken",
                        correlation, 1000000);
            }
            log.info("created all messages");

            IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
                public void execute(int count) throws Exception {
                    correlationService.send("channel", "<xml>Hello World!</xml>");
                }
            }, new IWaitForCallback() {
                public void call() throws Exception {
                    latch.await(360, TimeUnit.SECONDS);
                }
            }, false));
        }
    });
}