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.netflix.curator.x.discovery.TestServiceCache.java

@Test
public void testInitialLoad() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);//from  w  ww .  ja v a  2s.  com
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class)
                .basePath("/discovery").client(client).build();
        closeables.add(discovery);
        discovery.start();

        ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache);

        final CountDownLatch latch = new CountDownLatch(3);
        ServiceCacheListener listener = new ServiceCacheListener() {
            @Override
            public void cacheChanged() {
                latch.countDown();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        cache.addListener(listener);
        cache.start();

        ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10064).build();
        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10065).build();
        ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10066).build();
        discovery.registerService(instance1);
        discovery.registerService(instance2);
        discovery.registerService(instance3);

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        ServiceCache<String> cache2 = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache2);
        cache2.start();

        Assert.assertEquals(cache2.getInstances().size(), 3);
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

private Executor mockDispatchWorker(CountDownLatch latch) {

    Executor mockWorker = new Executor() {
        @Override//from   w  ww  .j  av a2s.  c o m
        public void execute(Runnable runnable) {
            logger.info("execute:{}", runnable.getClass());
            try {
                runnable.run();
            } finally {
                latch.countDown();
            }
        }
    };
    return Mockito.spy(mockWorker);
}

From source file:org.eclipse.hono.example.ExampleSender.java

/**
 * Connects to the Hono server./* w w w  .j  a  va 2 s .co m*/
 */
@PostConstruct
public void prepare() {

    LOG.info("starting sender");
    final CountDownLatch startup = new CountDownLatch(1);
    ctx = vertx.getOrCreateContext();
    final Future<RegistrationResult> startupTracker = Future.future();
    startupTracker.setHandler(done -> {
        if (done.succeeded()) {
            startup.countDown();
        } else {
            LOG.error("Error occurred during initialization: {}", done.cause().getMessage());
        }
    });

    ctx.runOnContext(go -> {
        /* step 1: connect Hono client */
        final Future<HonoClient> connectionTracker = Future.future();
        client.connect(getClientOptions(), connectionTracker.completer());
        connectionTracker.compose(v -> {
            /* step 2: create a registration client */
            return getRegistrationClient();
        }).compose(regClient -> {
            /* step 3: register a device */
            Future<RegistrationResult> regResultTracker = Future.future();
            regClient.register(deviceId, null, regResultTracker.completer());
            return regResultTracker;
        }).compose(regResult -> {
            /* step 4: handle result of registration */
            if (regResult.getStatus() == HTTP_CREATED || regResult.getStatus() == HTTP_CONFLICT) {
                LOG.info("device registered");
                startupTracker.complete();
            } else {
                startupTracker.fail(String.format("Failed to register device [%s]: %s", deviceId, regResult));
            }
        }, startupTracker);
    });

    try {
        if (!startup.await(5, TimeUnit.SECONDS)) {
            LOG.error("shutting down");
            vertx.close();
        }
    } catch (InterruptedException e) {
        // nothing to do
    }
}

From source file:com.yahoo.gondola.container.ZookeeperRegistryClientTest.java

private void testGetEntries(RegistryClient writer, RegistryClient reader, boolean remote) throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    InetSocketAddress addr = new InetSocketAddress(1234);
    if (remote) {
        reader.addListener(entry -> {
            if (entry.gondolaAddress.equals(addr)) {
                latch.countDown();
            }/*from ww w .  j  a  v  a2  s  . co  m*/
        });
    }

    String hostId = writer.register(SITE_1_HOST_3_CLUSTERS, addr, URI.create("https://api1.yahoo.com:4443"));

    if (remote) {
        latch.await();
    }

    List<RegistryClient.Entry> writerEntries = writer.getEntries().entrySet().stream().map(Map.Entry::getValue)
            .filter(e -> e.hostId.equals(hostId)).collect(Collectors.toList());

    assertEquals(writerEntries.size(), 1);

    Map<String, RegistryClient.Entry> readerEntries = reader.getEntries();
    assertEquals(readerEntries.size(), 1);

    for (RegistryClient.Entry e : writerEntries) {
        RegistryClient.Entry readerEntry = readerEntries.get(e.hostId);
        assertEquals(readerEntry.hostId, e.hostId);
        assertEquals(readerEntry.gondolaAddress, e.gondolaAddress);
    }
}

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

private void readAndCheck() throws Exception {
    // reread a contact
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getContacts().getAsync(contact.getId()), new FutureCallback<IContact>() {
        @Override//from   w ww.ja va 2s. co  m
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IContact result) {
            contact = result;
            try {
                Class<?> cls = contact.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceContact.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(property.getPrimitiveValue().toValue(), getter.invoke(contact));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:com.microsoft.office.integration.test.EventsAsyncTestCase.java

private void readAndCheck() throws Exception {
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getEvents().getAsync(event.getId()), new FutureCallback<IEvent>() {
        public void onFailure(Throwable t) {
            reportError(t);/*from w w  w . j av  a 2s  .c om*/
            cdl.countDown();
        }

        public void onSuccess(IEvent result) {
            try {
                event = result;
                Class<?> cls = event.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceEvent.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(getter.invoke(event), property.getPrimitiveValue().toValue());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:edu.umich.robot.HeadlessApplication.java

/**
 * <p>//from  w w  w.j  ava  2 s.c om
 * Start Soar, wait for timeout or Soar to stop.
 * 
 * @param controller
 *            Simulation controller initialized.
 * @throws InterruptedException
 *             Thrown on thread interrupt.
 */
private void run(Controller controller) throws InterruptedException {
    final CountDownLatch doneSignal = new CountDownLatch(1);

    Thread shutdownHook = new Thread() {
        @Override
        public void run() {
            logger.warn("Shutdown detected.");
            shutdown.set(true);
            doneSignal.countDown();
        }
    };

    Runtime.getRuntime().addShutdownHook(shutdownHook);

    try {
        controller.addListener(SoarStoppedEvent.class, new RobotEventListener() {
            public void onEvent(RobotEvent event) {
                logger.info("Soar stop detected.");
                doneSignal.countDown();
            }
        });

        ScheduledExecutorService schexec = MoreExecutors
                .getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1));
        ScheduledFuture<?> task = null;
        if (seconds > 0) {
            task = schexec.schedule(new Runnable() {
                public void run() {
                    logger.info("Time up.");
                    doneSignal.countDown();
                }
            }, seconds, TimeUnit.SECONDS);
        }

        controller.startSoar(cycles);

        doneSignal.await();

        if (task != null)
            task.cancel(true);
        schexec.shutdown();
    } finally {
        if (!shutdown.get())
            Runtime.getRuntime().removeShutdownHook(shutdownHook);
    }
}

From source file:com.github.oscerd.component.cassandra.embedded.CassandraBaseTest.java

@Override
public void doPostSetup() {
    String id = RandomStringUtils.random(12, "0123456789abcdefghijklmnopqrstuvwxyz");
    fs = new Farsandra();
    fs.withVersion("2.0.3");
    fs.withCleanInstanceOnStart(true);/*from   w  ww  . j  ava 2 s . c o  m*/
    fs.withInstanceName("target" + File.separator + id);
    fs.withCreateConfigurationFiles(true);
    fs.withHost("localhost");
    fs.withSeeds(Arrays.asList("localhost"));
    final CountDownLatch started = new CountDownLatch(1);
    fs.getManager().addOutLineHandler(new LineHandler() {
        @Override
        public void handleLine(String line) {
            if (line.contains("Listening for thrift clients...")) {
                started.countDown();
            }
        }
    });
    fs.getManager().addProcessHandler(new ProcessHandler() {
        @Override
        public void handleTermination(int exitValue) {
            started.countDown();
        }
    });
    fs.start();
    try {
        started.await();
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect();
    session.execute("CREATE KEYSPACE IF NOT EXISTS simplex WITH replication "
            + "= {'class':'SimpleStrategy', 'replication_factor':3};");
    session.execute("CREATE TABLE IF NOT EXISTS simplex.songs (" + "id int PRIMARY KEY," + "title text,"
            + "album text," + "artist text," + "tags set<text>," + "data blob," + ");");
    session.execute("CREATE INDEX IF NOT EXISTS album_idx ON simplex.songs(album);");
    session.execute("CREATE INDEX IF NOT EXISTS title_idx ON simplex.songs(title);");
    PreparedStatement statement = session.prepare(
            "INSERT INTO simplex.songs " + "(id, title, album, artist, tags) " + "VALUES (?, ?, ?, ?, ?);");
    BoundStatement boundStatement = new BoundStatement(statement);
    List<Song> songList = new ArrayList<Song>();
    prepareStartingData(songList);
    Iterator it = songList.iterator();
    while (it.hasNext()) {
        Song song = (Song) it.next();
        ResultSet res = session.execute(boundStatement.bind(song.getId(), song.getTitle(), song.getAlbum(),
                song.getArtist(), song.getTags()));
    }
    session.close();
    cluster.close();
    try {
        Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

@Test
public void shouldNotClose() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    try {//from   www .  java  2  s.  com
        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.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitorTest.java

@Test
public void testMonitorInStoppedStatus() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);

    SdkCredentialsFileContentMonitor monitor = new SdkCredentialsFileContentMonitor(targetFile,
            MONITOR_POLLING_INTERVAL_MILLIS, new FileAlterationListenerAdaptor() {

                @Override//from w  ww  .ja  va 2  s  .co m
                public void onFileChange(final File changedFile) {
                    System.err.println("stopped");
                    latch.countDown();
                }
            });
    monitor.setDebugMode(true);
    monitor.start();
    monitor.stop();

    touch(targetFile);

    long waitTime = MONITOR_POLLING_INTERVAL_MILLIS * 2;
    Assert.assertFalse("Who counted it down to zero???", latch.await(waitTime, TimeUnit.MILLISECONDS));
}