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.couch.db.CouchManager.java

protected synchronized void threadedExecute(final Set<? extends CouchDocumentAction> actions)
        throws CouchDBException {
    if (exec == null) {
        exec = Executors.newCachedThreadPool();
    }//from ww w.jav a2s.  c om

    final CountDownLatch latch = new CountDownLatch(actions.size());
    for (final CouchDocumentAction action : actions) {
        action.prepareExecution(latch, this);
        exec.execute(action);
    }

    synchronized (latch) {
        while (latch.getCount() > 0) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Waiting for " + latch.getCount() + " actions to complete.");
            }

            try {
                latch.await(2, TimeUnit.SECONDS);
            } catch (final InterruptedException e) {
                break;
            }
        }
    }

    final List<Throwable> errors = new ArrayList<Throwable>();
    for (final CouchDocumentAction action : actions) {
        if (action.getError() != null) {
            errors.add(action.getError());
        }
    }

    if (!errors.isEmpty()) {
        throw new CouchDBException("Failed to execute %d actions.", errors.size()).withNestedErrors(errors);
    }
}

From source file:EventingTest.java

public void testEventing() throws Exception {

    meshKeeper.launcher().waitForAvailableAgents(60000);
    HostProperties[] hosts = meshKeeper.launcher().getAvailableAgents();

    MeshContainer c1 = meshKeeper.launcher().launchMeshContainer(hosts[0].getAgentId());
    MeshContainer c2 = meshKeeper.launcher()
            .launchMeshContainer((hosts.length > 1 ? hosts[1] : hosts[0]).getAgentId());

    Greeter g1 = new Greeter();
    g1.name = "machine1";

    Greeter g2 = new Greeter();
    g2.name = "machine2";

    //Let's host them in their containers,
    //Note that we replace the actual references
    //with their proxy counterparts.
    g1 = c1.host(g1.name, g1);/*w w w  .j  a va  2 s  .co  m*/
    g2 = c2.host(g2.name, g2);

    //Set up an event listener to wait for the hellos
    final CountDownLatch hellos = new CountDownLatch(2);
    final ArrayList<Exception> errors = new ArrayList<Exception>();
    MeshEventListener listener = new MeshEventListener() {

        public void onEvent(MeshEvent event) {
            switch (event.getType()) {
            case HELLO: {
                LOG.info("Got : " + event.getAttachment() + " from " + event.getSource());
                hellos.countDown();
                break;
            }
            case SAY_HELLO: {
                break;
            }

            case ERROR:
            default: {
                Exception e = event.getAttachment();
                LOG.error("Error from: " + event.getSource(), e);
                errors.add(e);

                while (hellos.getCount() > 0) {
                    hellos.countDown();
                }
            }
            }
        }
    };
    meshKeeper.eventing().openEventListener(listener, EVENT_TOPIC + ".*");

    //Start the
    g1.startListening();
    g2.startListening();
    meshKeeper.eventing().sendEvent(new MeshEvent(SAY_HELLO, "controller", null), EVENT_TOPIC + ".control");

    hellos.await(10, TimeUnit.SECONDS);
    Thread.sleep(2000);
    assertTrue("There were errors", errors.isEmpty());
    c1.close();
    c2.close();

    meshKeeper.eventing().closeEventListener(listener, EVENT_TOPIC + ".*");
}

From source file:org.apache.cassandra.dht.BootStrapper.java

public void bootstrap() throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Beginning bootstrap process");

    final Multimap<String, Map.Entry<InetAddress, Collection<Range>>> rangesToFetch = HashMultimap.create();

    int requests = 0;
    for (String table : DatabaseDescriptor.getNonSystemTables()) {
        Map<InetAddress, Collection<Range>> workMap = getWorkMap(getRangesWithSources(table)).asMap();
        for (Map.Entry<InetAddress, Collection<Range>> entry : workMap.entrySet()) {
            requests++;//from   www  .  ja v  a2 s .  c o m
            rangesToFetch.put(table, entry);
        }
    }

    final CountDownLatch latch = new CountDownLatch(requests);
    for (final String table : rangesToFetch.keySet()) {
        /* Send messages to respective folks to stream data over to me */
        for (Map.Entry<InetAddress, Collection<Range>> entry : rangesToFetch.get(table)) {
            final InetAddress source = entry.getKey();
            Collection<Range> ranges = entry.getValue();
            final Runnable callback = new Runnable() {
                public void run() {
                    latch.countDown();
                    if (logger.isDebugEnabled())
                        logger.debug(String.format("Removed %s/%s as a bootstrap source; remaining is %s",
                                source, table, latch.getCount()));
                }
            };
            if (logger.isDebugEnabled())
                logger.debug(
                        "Bootstrapping from " + source + " ranges " + StringUtils.join(entry.getValue(), ", "));
            StreamIn.requestRanges(source, table, entry.getValue(), callback, OperationType.BOOTSTRAP);
        }
    }

    try {
        latch.await();
        StorageService.instance.finishBootstrapping();
    } catch (InterruptedException e) {
        throw new AssertionError(e);
    }
}

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

public static Runnable reader(int k, JoinableFileManager manager, File f, CountDownLatch masterLatch,
        CountDownLatch readBeginLatch, CountDownLatch readEndLatch, CountDownLatch deleteEndLatch,
        boolean binaryContent) {
    return () -> {
        Thread.currentThread().setName("openInputStream-" + k);
        System.out.println("Starting: " + Thread.currentThread().getName());

        if (deleteEndLatch != null) {
            try {
                System.out.println("awaiting delete latch");
                deleteEndLatch.await();/*from   www . j a  v a  2  s .  c  o m*/
            } catch (InterruptedException e) {
                return;
            }
        }

        if (readBeginLatch != null) {
            System.out.println("Counting down read-begin latch");
            readBeginLatch.countDown();
            try {
                System.out.println("awaiting read-begin latch");
                readBeginLatch.await();
            } catch (InterruptedException e) {
                return;
            }
        }

        try (InputStream s = manager.openInputStream(f)) {
            if (binaryContent) {
                byte[] data = IOUtils.toByteArray(s);
                System.out.println(Thread.currentThread().getName() + ": Read " + data.length + " bytes.");
            } else {
                System.out.println(Thread.currentThread().getName() + ": " + IOUtils.toString(s));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (readEndLatch != null) {
                System.out.println("Counting down read-end latch");
                readEndLatch.countDown();
            }
            System.out.println("Counting down master latch");
            masterLatch.countDown();
            System.out.println(String.format("[%s] Count down after %s read thread: %s",
                    Thread.currentThread().getName(), k, masterLatch.getCount()));
        }
    };
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

private void validateSSLConfigurationIsReloaded(Settings settings, Environment env,
        Consumer<SSLContext> preChecks, Runnable modificationFunction, Consumer<SSLContext> postChecks)
        throws Exception {

    final CountDownLatch reloadLatch = new CountDownLatch(1);
    final SSLService sslService = new SSLService(settings, env);
    final SSLConfiguration config = sslService.sslConfiguration(Settings.EMPTY);
    new SSLConfigurationReloader(settings, env, sslService, resourceWatcherService) {
        @Override//w w w .  java 2s .c  o m
        void reloadSSLContext(SSLConfiguration configuration) {
            super.reloadSSLContext(configuration);
            reloadLatch.countDown();
        }
    };
    // Baseline checks
    preChecks.accept(sslService.sslContextHolder(config).sslContext());

    assertEquals("nothing should have called reload", 1, reloadLatch.getCount());

    // modify
    modificationFunction.run();
    reloadLatch.await();
    // checks after reload
    postChecks.accept(sslService.sslContextHolder(config).sslContext());
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest.java

@Test
public void shouldReloadClassLoaderWhileDoingEvalInSeparateThread() throws Exception {
    final AtomicBoolean fail = new AtomicBoolean(false);
    final AtomicInteger counter = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Color> color = new AtomicReference<>(Color.RED);

    final GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine();

    try {//from w  w w. j av  a2s.c  o  m
        scriptEngine.eval("Color.BLACK");
        fail("Should fail as class is not yet imported");
    } catch (ScriptException se) {
        // should get here as Color.BLACK is not imported yet.
        logger.info("Failed to execute Color.BLACK as expected.");
    }

    final Thread evalThread = new Thread(() -> {
        try {
            // execute scripts until the other thread releases this latch (i.e. after import)
            while (latch.getCount() == 1) {
                scriptEngine.eval("1+1");
                counter.incrementAndGet();
            }

            color.set((Color) scriptEngine.eval("Color.BLACK"));
        } catch (Exception se) {
            fail.set(true);
        }
    }, "test-reload-classloader-1");

    evalThread.start();

    // let the first thread execute a bit.
    Thread.sleep(1000);

    final Thread importThread = new Thread(() -> {
        logger.info("Importing java.awt.Color...");
        final Set<String> imports = new HashSet<String>() {
            {
                add("import java.awt.Color");
            }
        };
        scriptEngine.addImports(imports);
        latch.countDown();
    }, "test-reload-classloader-2");

    importThread.start();

    // block until both threads are done
    importThread.join();
    evalThread.join();

    assertEquals(Color.BLACK, color.get());
    assertThat(counter.get(), greaterThan(0));
    assertFalse(fail.get());
}

From source file:org.springframework.kafka.listener.TransactionalContainerTests.java

@SuppressWarnings("unchecked")
@Test/*w  w w .  jav a 2 s .co  m*/
public void testRollbackRecord() throws Exception {
    logger.info("Start testRollbackRecord");
    Map<String, Object> props = KafkaTestUtils.consumerProps("txTest1", "false", embeddedKafka);
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "group");
    props.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
    DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
    ContainerProperties containerProps = new ContainerProperties(topic1, topic2);
    containerProps.setGroupId("group");
    containerProps.setPollTimeout(10_000);

    Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
    senderProps.put(ProducerConfig.RETRIES_CONFIG, 1);
    DefaultKafkaProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
    pf.setTransactionIdPrefix("rr.");

    final KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
    final AtomicBoolean failed = new AtomicBoolean();
    final CountDownLatch latch = new CountDownLatch(3);
    final AtomicReference<String> transactionalId = new AtomicReference<>();
    containerProps.setMessageListener((MessageListener<Integer, String>) message -> {
        latch.countDown();
        if (failed.compareAndSet(false, true)) {
            throw new RuntimeException("fail");
        }
        /*
         * Send a message to topic2 and wait for it so we don't stop the container too soon.
         */
        if (message.topic().equals(topic1)) {
            template.send(topic2, "bar");
            template.flush();
            transactionalId.set(KafkaTestUtils.getPropertyValue(
                    ProducerFactoryUtils.getTransactionalResourceHolder(pf).getProducer(),
                    "delegate.transactionManager.transactionalId", String.class));
        }
    });

    @SuppressWarnings({ "rawtypes" })
    KafkaTransactionManager tm = new KafkaTransactionManager(pf);
    containerProps.setTransactionManager(tm);
    KafkaMessageListenerContainer<Integer, String> container = new KafkaMessageListenerContainer<>(cf,
            containerProps);
    container.setBeanName("testRollbackRecord");
    container.start();

    template.setDefaultTopic(topic1);
    template.executeInTransaction(t -> {
        template.sendDefault(0, 0, "foo");
        return null;
    });
    assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
    container.stop();
    Consumer<Integer, String> consumer = cf.createConsumer();
    final CountDownLatch subsLatch = new CountDownLatch(1);
    consumer.subscribe(Arrays.asList(topic1), new ConsumerRebalanceListener() {

        @Override
        public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
            // empty
        }

        @Override
        public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
            subsLatch.countDown();
        }

    });
    ConsumerRecords<Integer, String> records = null;
    int n = 0;
    while (subsLatch.getCount() > 0 && n++ < 600) {
        records = consumer.poll(Duration.ofMillis(100));
    }
    assertThat(subsLatch.await(1, TimeUnit.MILLISECONDS)).isTrue();
    assertThat(records.count()).isEqualTo(0);
    // depending on timing, the position might include the offset representing the commit in the log
    assertThat(consumer.position(new TopicPartition(topic1, 0))).isGreaterThanOrEqualTo(1L);
    assertThat(transactionalId.get()).startsWith("rr.group.txTopic");
    assertThat(KafkaTestUtils.getPropertyValue(pf, "consumerProducers", Map.class)).isEmpty();
    logger.info("Stop testRollbackRecord");
    pf.destroy();
    consumer.close();
}

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

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

    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/1", "1",
            "CXF in Action1", startSignal, doneSignal));
    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/2", "2",
            "CXF in Action2", startSignal, doneSignal));
    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/3", "3",
            "CXF in Action3", startSignal, doneSignal));
    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/4", "4",
            "CXF in Action4", startSignal, doneSignal));
    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/5", "5",
            "CXF in Action5", startSignal, doneSignal));

    startSignal.countDown();/*from w  w w .j a  v a  2  s.  c  o m*/
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
}

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

@Test
public void twoFileReaders_CleanupFileEntryOnLastClose() throws Exception {
    String src = "This is a test";

    File f = temp.newFile();/*w w w  .  jav  a 2 s  .  co m*/
    FileUtils.write(f, src);

    int count = 2;
    CountDownLatch start = new CountDownLatch(count);
    CountDownLatch end = new CountDownLatch(count);

    Logger logger = LoggerFactory.getLogger(getClass());
    ExecutorService executor = Executors.newCachedThreadPool();
    for (int i = 0; i < count; i++) {
        logger.info("Starting: {}", i);
        executor.execute(() -> {
            logger.info("Signaling thread: {} has started", Thread.currentThread().getName());
            start.countDown();
            try {
                logger.info("Waiting for other thread(s) to start...");
                start.await(3, TimeUnit.SECONDS);

                assertThat("Threads did not start correctly!", start.getCount(), equalTo(0L));

                logger.info("Opening: {}", f);

                try (InputStream in = mgr.openInputStream(f)) {
                    assertThat(IOUtils.toString(in), equalTo(src));
                } catch (IOException e) {
                    e.printStackTrace();
                    fail("Cannot open: " + f);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                fail("Interrupted");
            } finally {
                logger.info("Signaling thread: {} has ended", Thread.currentThread().getName());
                end.countDown();
            }
        });
    }

    logger.info("Waiting for end of threads");
    end.await(5, TimeUnit.SECONDS);

    assertThat("Threads did not end correctly!", end.getCount(), equalTo(0L));

    AtomicInteger counter = new AtomicInteger(0);
    mgr.getFileTree().forAll(entry -> true, entry -> counter.incrementAndGet());

    assertThat("FileEntry instance was not removed after closing!", counter.get(), equalTo(0));
}

From source file:org.openhab.io.transport.modbus.test.SmokeTest.java

@SuppressWarnings("null")
@Test//from   ww  w. j a v a 2  s  .  c o m
public void testPoolConfigurationListenerAndChanges() {
    AtomicInteger expectedCount = new AtomicInteger();
    AtomicInteger unexpectedCount = new AtomicInteger();
    CountDownLatch callbackCalled = new CountDownLatch(2);
    modbusManager.addListener(new ModbusManagerListener() {

        @Override
        public void onEndpointPoolConfigurationSet(ModbusSlaveEndpoint endpoint,
                EndpointPoolConfiguration configuration) {
            if ((callbackCalled.getCount() == 2L && configuration.getConnectMaxTries() == 50)
                    || (callbackCalled.getCount() == 1L && configuration == null)) {
                expectedCount.incrementAndGet();
            } else {
                unexpectedCount.incrementAndGet();
            }
            callbackCalled.countDown();
        }
    });
    EndpointPoolConfiguration defaultConfig = modbusManager.getEndpointPoolConfiguration(getEndpoint());
    assertThat(defaultConfig, is(notNullValue()));

    EndpointPoolConfiguration newConfig = new EndpointPoolConfiguration();
    newConfig.setConnectMaxTries(50);
    modbusManager.setEndpointPoolConfiguration(getEndpoint(), newConfig);
    assertThat(modbusManager.getEndpointPoolConfiguration(getEndpoint()).getConnectMaxTries(), is(equalTo(50)));
    assertThat(modbusManager.getEndpointPoolConfiguration(getEndpoint()), is(not(equalTo(defaultConfig))));

    assertThat(unexpectedCount.get(), is(equalTo(0)));
    assertThat(callbackCalled.getCount(), is(equalTo(1L)));

    // Reset config
    modbusManager.setEndpointPoolConfiguration(getEndpoint(), null);
    // Should match default
    assertThat(modbusManager.getEndpointPoolConfiguration(getEndpoint()), is(equalTo(defaultConfig)));

    // change callback should have been called twice (countdown at zero)
    assertThat(unexpectedCount.get(), is(equalTo(0)));
    assertThat(expectedCount.get(), is(equalTo(2)));
    assertThat(callbackCalled.getCount(), is(equalTo(0L)));

}