Example usage for java.util.concurrent CountDownLatch await

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

Introduction

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

Prototype

public void await() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted .

Usage

From source file:info.archinnov.achilles.test.integration.tests.AsyncQueryIT.java

@Test
public void should_allow_native_and_typed_query_with_bound_statement() throws Exception {
    //Given//from  w  w w  .  j av  a  2 s .c o m
    final long id = RandomUtils.nextLong(0, Long.MAX_VALUE);
    final Session session = asyncManager.getNativeSession();
    final PreparedStatement insertPs = session
            .prepare(insertInto(CompleteBean.TABLE_NAME).value("id", bindMarker("id"))
                    .value("label", bindMarker("label")).value("age_in_years", bindMarker("age")));
    final BoundStatement insertBs = insertPs.bind(id, "label", 32L);

    final CountDownLatch latch1 = new CountDownLatch(1);
    asyncManager.nativeQuery(insertBs).execute(countDownLatch(latch1));

    latch1.await();

    final PreparedStatement selectPs = session
            .prepare(select().from(CompleteBean.TABLE_NAME).where(eq("id", bindMarker("id"))));
    final BoundStatement selectBs = selectPs.bind(id);

    //When
    final CountDownLatch latch2 = new CountDownLatch(2);
    final AchillesFuture<CompleteBean> foundWithProxy = asyncManager.typedQuery(CompleteBean.class, selectBs)
            .getFirst(countDownLatch(latch2));
    final AchillesFuture<CompleteBean> foundRaw = asyncManager.rawTypedQuery(CompleteBean.class, selectBs)
            .getFirst(countDownLatch(latch2));

    latch2.await();

    final CompleteBean entityWithProxy = foundWithProxy.get();
    final CompleteBean entityRaw = foundRaw.get();

    //Then
    assertThat(entityWithProxy).isNotNull();
    assertThat(entityWithProxy.getLabel()).isEqualTo("label");
    assertThat(entityWithProxy.getAge()).isEqualTo(32L);

    assertThat(entityRaw).isNotNull();
    assertThat(entityRaw.getLabel()).isEqualTo("label");
    assertThat(entityRaw.getAge()).isEqualTo(32L);
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkJMSProducerWrapper.java

private void runProducers(long rate, long duration) {

    BigDecimal bd = new BigDecimal(1000000).divide(new BigDecimal(rate), BigDecimal.ROUND_HALF_DOWN);
    long delayInMicroSeconds;
    try {/*from  w  w w.  ja v a  2s  .  co  m*/
        delayInMicroSeconds = bd.longValueExact();
    } catch (ArithmeticException e) {
        delayInMicroSeconds = bd.longValue();
        log().warn("Publish rate cannot be expressed as a precise microsecond value, rounding to nearest value "
                + "[actualDelay: " + delayInMicroSeconds + "]");
    }

    int producersNeeded = (int) (rate / getPartConfig().getMaxConsumerRatePerThread());
    if (producersNeeded == 0) {
        producersNeeded++;
    }

    log.debug("Running " + producersNeeded + " producers for " + duration + "s");
    producers = new ArrayList<BenchmarkProducer>(producersNeeded);
    sendingDelay = delayInMicroSeconds * producersNeeded;
    executor = new ScheduledThreadPoolExecutor(producersNeeded);

    for (int i = 0; i < producersNeeded; i++) {
        try {
            BenchmarkProducer producer = new BenchmarkProducer(this);
            producer.start();
            producer.setMessageCounter(getProbe());
            producers.add(producer);
        } catch (Exception e) {
            throw new BenchmarkConfigurationException("Unable to create BenchmarkProducer instance", e);
        }
    }
    for (BenchmarkProducer producer : producers) {
        // TODO should really hold onto these and monitor for failures until the
        // executor is shutdown
        executor.scheduleAtFixedRate(new MessageSender(producer), 0, sendingDelay, sendingDelayUnit);
    }

    final CountDownLatch latch = new CountDownLatch(1);

    new ScheduledThreadPoolExecutor(1).schedule(new Runnable() {
        public void run() {
            try {
                log.debug("Shutting down producers.");
                executor.shutdown();
                for (BenchmarkProducer producer : producers) {
                    try {
                        producer.release();
                    } catch (Exception e) {
                        log().error("Error releasing producer.");
                    }
                }
                latch.countDown();
            } catch (Exception e) {
            }
        }
    }, duration, TimeUnit.SECONDS);

    try {
        latch.await();
    } catch (InterruptedException ie) {
        log().warn("Producer run has been interrupted ...");
    }
}

From source file:com.uber.tchannel.ping.PingClient.java

public void run() throws Exception {
    TChannel tchannel = new TChannel.Builder("ping-client").build();
    SubChannel subChannel = tchannel.makeSubChannel("ping-server");
    final ConcurrentHashMap<String, Integer> msgs = new ConcurrentHashMap<String, Integer>();
    final CountDownLatch done = new CountDownLatch(requests);

    for (int i = 0; i < requests; i++) {
        JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
                .setBody(new Ping("{'key': 'ping?'}")).setHeader("some", "header").setTimeout(100 + i).build();
        TFuture<JsonResponse<Pong>> f = subChannel.send(request, InetAddress.getByName(host), port);

        f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
            @Override/*from   w w w . j  a  va  2s. co m*/
            public void onResponse(JsonResponse<Pong> pongResponse) {
                done.countDown();
                String msg = pongResponse.toString();
                if (msgs.containsKey(msg)) {
                    msgs.put(msg, msgs.get(msg) + 1);
                } else {
                    msgs.put(msg, 1);
                }
            }
        });
    }

    done.await();
    for (String msg : msgs.keySet()) {
        System.out.println(String.format("%s\n\tcount:%d", msg, msgs.get(msg)));
    }

    tchannel.shutdown(false);
}

From source file:com.fusesource.forge.jmstest.tests.simple.SimpleConsumer.java

protected void run() {
    Connection con = null;//from   w w  w . ja va 2  s . c o m
    Session session = null;
    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);
    try {
        con = getConnection();
        session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dest = getDestinationProvider().getDestination(session, "queue:TEST");
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                String grp = null;
                long nr = 0L;
                try {
                    grp = msg.getStringProperty("JMSXGroupID");
                    nr = msg.getLongProperty("MsgNr");
                } catch (JMSException jme) {
                }
                log().info("Received Message Group=(" + grp + ") MsgNr=" + nr);
                latch.countDown();
            }
        });
        con.start();
        latch.await();
        con.close();
    } catch (Exception e) {
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java

/**
 * Helper method to block the calling thread until the latch is zeroed by some other task.
 * @param latch Latch to wait for./*from  www. j a v  a  2 s.co  m*/
 * @param latchName Name to be used in log messages for the given latch.
 */
private void waitForLatchUnlock(CountDownLatch latch, String latchName) {
    try {
        Log.i(TAG, "Waiting for " + latchName + " latch release...");
        latch.await();
        Log.i(TAG, latchName + " latch released!");
    } catch (InterruptedException ie) {
        Log.w(TAG, "Warning: continuing before " + latchName + " latch was released");
    }
}