Example usage for java.util.concurrent CountDownLatch CountDownLatch

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

Introduction

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

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

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

@Test
public void testConnect() throws Exception {
    Connection subConnection = connectionFactory.createConnection();
    final int count = 1000;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    Subscription subscription = subConnection.subscribe("foo", new MessageHandler() {
        @Override//w ww . j  av  a2  s  . co m
        public void onMessage(Message message) {
            countDownLatch.countDown();
            //System.out.println("GOT " + message);
        }
    });

    Connection pubConnection = new ConnectionFactory().createConnection();

    for (int i = 0; i < count; i++) {
        String test = "Test" + i;
        pubConnection.publish("foo", "bah", test.getBytes());
    }

    countDownLatch.await(2, TimeUnit.SECONDS);
    Assert.assertEquals(0, countDownLatch.getCount());
    pubConnection.close();
    subConnection.close();
}

From source file:org.eclipse.hono.event.impl.ForwardingEventDownstreamAdapterTest.java

@Test
public void testProcessMessageForwardsEventMessageToDownstreamSender() throws InterruptedException {

    final Vertx vertx = mock(Vertx.class);
    final UpstreamReceiver client = newClient();
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final ProtonDelivery downstreamDelivery = mock(ProtonDelivery.class);
    when(downstreamDelivery.getRemoteState()).thenReturn(ACCEPTED);
    when(downstreamDelivery.remotelySettled()).thenReturn(true);

    // GIVEN an adapter with a connection to a downstream container
    final CountDownLatch latch = new CountDownLatch(1);
    ProtonSender sender = newMockSender(false);
    when(sender.send(any(Message.class), any(Handler.class))).then(invocation -> {
        latch.countDown();//from w w  w.j  a  va 2 s.c o m
        invocation.getArgumentAt(1, Handler.class).handle(downstreamDelivery);
        return null;
    });
    ForwardingEventDownstreamAdapter adapter = new ForwardingEventDownstreamAdapter(vertx,
            newMockSenderFactory(sender));
    adapter.setDownstreamConnectionFactory(newMockConnectionFactory(false));
    adapter.start(Future.future());
    adapter.addSender(client, sender);

    // WHEN processing an event
    Message msg = ProtonHelper.message(EVENT_MSG_CONTENT);
    MessageHelper.addDeviceId(msg, DEVICE_ID);
    adapter.processMessage(client, delivery, msg);

    // THEN the message has been delivered to the downstream container
    assertTrue(latch.await(1, TimeUnit.SECONDS));
    // and disposition was returned
    verify(delivery).disposition(ACCEPTED, true);
}

From source file:com.googlecode.ehcache.annotations.integration.SelfPopulatingMethodTest.java

/**
 * Verify that setting selfPopulating=true will guarantee only 1 invocation
 * of the cached method./*from   w w  w  .j a v  a 2s  .  c  o m*/
 * 
 * @throws Exception
 */
@Test //(timeout=1000)
public void testSelfPopulatingTrue() throws Exception {
    final CountDownLatch threadRunningLatch = new CountDownLatch(6);
    final CountDownLatch proceedLatch = new CountDownLatch(1);
    this.selfPopulatingTestInterface.setThreadRunningLatch(threadRunningLatch);
    this.selfPopulatingTestInterface.setProccedLatch(proceedLatch);

    Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingAInvocationCount());
    Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingBInvocationCount());

    final ThreadGroupRunner threadGroup = new ThreadGroupRunner("testSelfPopulatingTrue-", true);

    threadGroup.addTask(2, new Runnable() {
        public void run() {
            threadRunningLatch.countDown();
            logger.trace("Calling blockingA(test2)");
            selfPopulatingTestInterface.blockingA("test2");
        }
    });
    threadGroup.addTask(2, new Runnable() {
        public void run() {
            threadRunningLatch.countDown();
            logger.trace("Calling blockingB(test2)");
            selfPopulatingTestInterface.blockingB("test2");
        }
    });

    threadGroup.start();

    // wait for both threads to get going
    logger.trace("Waiting for threads to start");
    threadRunningLatch.await();

    // Let both threads complete
    logger.trace("Signal threads to proceed");
    proceedLatch.countDown();

    logger.trace("Waiting for threads to complete");
    threadGroup.join();

    // verify only 1 call between method A and method B
    Assert.assertEquals(1, this.selfPopulatingTestInterface.getBlockingAInvocationCount());
    Assert.assertEquals(1, this.selfPopulatingTestInterface.getBlockingBInvocationCount());
}

From source file:net.spy.memcached.couch.TestingClient.java

public HttpFuture<String> asyncHttpPut(String uri, String document) throws UnsupportedEncodingException {
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout);

    HttpRequest request = new BasicHttpEntityEnclosingRequest("PUT", uri, HttpVersion.HTTP_1_1);
    StringEntity entity = new StringEntity(document);
    ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
    HttpOperationImpl op = new TestOperationImpl(request, new TestCallback() {
        private String json;

        @Override/*w  ww. ja  v a2  s. c  om*/
        public void receivedStatus(OperationStatus status) {
            crv.set(json, status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }

        @Override
        public void getData(String response) {
            json = response;
        }
    });
    crv.setOperation(op);
    addOp(op);
    return crv;
}

From source file:com.meltmedia.cadmium.core.git.DelayedGitServiceInitializer.java

/**
 * Basic constructor that creates a CountDownLatch with a count of 1.
 */
public DelayedGitServiceInitializer() {
    latch = new CountDownLatch(1);
}

From source file:com.couchbase.client.TestingClient.java

public HttpFuture<String> asyncHttpPut(String uri, String document) throws UnsupportedEncodingException {
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout);

    HttpRequest request = new BasicHttpEntityEnclosingRequest("PUT", uri, HttpVersion.HTTP_1_1);
    request.setHeader(new BasicHeader("Content-Type", "application/json"));
    StringEntity entity = new StringEntity(document);
    ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
    HttpOperationImpl op = new TestOperationPutImpl(request, new TestCallback() {
        private String json;

        @Override// www  .j  a va 2  s  . c o  m
        public void receivedStatus(OperationStatus status) {
            crv.set(json, status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }

        @Override
        public void getData(String response) {
            json = response;
        }
    });
    crv.setOperation(op);
    addOp(op);
    return crv;
}

From source file:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java

/**
 * Runs a number of threads which generate metrics.
 *///from  www  . ja  v  a2 s.c  om
public static void generateMetrics(final MetricRegistry metrics, final long metricsToGenerate, final int period,
        final TimeUnit periodTimeUnit, HadoopMetrics2Reporter metrics2Reporter, int numThreads)
        throws Exception {
    final ScheduledExecutorService pool = Executors.newScheduledThreadPool(numThreads);
    final CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        final int id = i;
        final int halfPeriod = (period / 2);
        Runnable task = new Runnable() {
            private long executions = 0;
            final Random r = new Random();

            @Override
            public void run() {
                if (executions >= metricsToGenerate) {
                    return;
                }
                metrics.counter("foo counter thread" + id).inc();
                executions++;
                if (executions < metricsToGenerate) {
                    pool.schedule(this, period + r.nextInt(halfPeriod), periodTimeUnit);
                } else {
                    latch.countDown();
                }
            }
        };
        pool.schedule(task, period, periodTimeUnit);
    }

    while (!latch.await(2, TimeUnit.SECONDS)) {
        metrics2Reporter.printQueueDebugMessage();
    }

    pool.shutdown();
    pool.awaitTermination(5000, TimeUnit.SECONDS);
}

From source file:com.solace.samples.BasicReplier.java

public void run(String... args) {
    System.out.println("BasicReplier initializing...");

    try {/*from w w  w  .  j  a  va2 s.  c o  m*/
        // Create an Mqtt client
        final MqttClient mqttClient = new MqttClient("tcp://" + args[0], "HelloWorldBasicReplier");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);

        // Connect the client
        System.out.println("Connecting to Solace broker: tcp://" + args[0]);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);

        // Topic filter the client will subscribe to receive requests
        final String requestTopic = "T/GettingStarted/request";

        // Callback - Anonymous inner-class for receiving request messages
        mqttClient.setCallback(new MqttCallback() {

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                try {
                    // Parse the received request message and convert payload to a JSONObject
                    Object payloadObj = parser.parse(new String(message.getPayload()));
                    JSONObject jsonPayload = (JSONObject) payloadObj;

                    // Get the correlationId and replyTo fields from the payload
                    String correlationId = (String) jsonPayload.get("correlationId");
                    String replyTo = (String) jsonPayload.get("replyTo");
                    String messageContent = (String) jsonPayload.get("message");

                    System.out.println("\nReceived a request message!" + "\n\tCorrel. Id: " + correlationId
                            + "\n\tReply To:   " + replyTo + "\n\tMessage:    " + messageContent + "\n");

                    // Create the response payload in JSON format and set correlationId
                    // to the id received in the request message above. Requestor will
                    // use this to correlate the response with its request message.
                    JSONObject obj = new JSONObject();
                    obj.put("correlationId", correlationId);
                    obj.put("message", "Sample Response");
                    String respPayload = obj.toJSONString();

                    // Create a response message and set the response payload
                    MqttMessage respMessage = new MqttMessage(respPayload.getBytes());
                    respMessage.setQos(0);

                    System.out.println("Sending response to: " + replyTo);

                    // Publish the response message to the replyTo topic retrieved 
                    // from the request message above
                    MqttTopic mqttTopic = mqttClient.getTopic(replyTo);
                    mqttTopic.publish(respMessage);

                    latch.countDown(); // unblock main thread
                } catch (ParseException ex) {
                    System.out.println("Exception parsing request message!");
                    ex.printStackTrace();
                }
            }

            public void connectionLost(Throwable cause) {
                System.out.println("Connection to Solace broker lost!" + cause.getMessage());
                latch.countDown();
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
            }

        });

        // Subscribe client to the topic filter with a QoS level of 0
        System.out.println("Subscribing client to request topic: " + requestTopic);
        mqttClient.subscribe(requestTopic, 0);

        System.out.println("Waiting for request message...");
        // Wait for till we have received a request and sent a response
        try {
            latch.await(); // block here until message received, and latch will flip
        } catch (InterruptedException e) {
            System.out.println("I was awoken while waiting");
        }

        // Disconnect the client
        mqttClient.disconnect();
        System.out.println("Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}

From source file:com.jbrisbin.vpc.jobsched.batch.BatchMessageHandler.java

public BatchMessage handleMessage(BatchMessage batch) throws Exception {
    log.debug("handling message: " + batch.toString());

    final BatchMessage results = new BatchMessage();
    results.setId(batch.getId());/*w  w  w  . ja  v a2  s  .c om*/

    // For waiting till our results are all back
    final CountDownLatch latch = new CountDownLatch(batch.getMessages().size());

    Queue resultsQueue = rabbitAdmin.declareQueue();
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(connectionFactory);
    listener.setAutoAck(true);
    listener.setQueues(resultsQueue);
    listener.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            String messageId = new String(message.getMessageProperties().getCorrelationId());
            String body = new String(message.getBody());
            results.getMessages().put(messageId, body);
            latch.countDown();
        }
    });
    listener.start();

    for (Map.Entry<String, String> msg : batch.getMessages().entrySet()) {
        final String[] parts = msg.getKey().split(":");
        template.send(parts[0], parts[1],
                new MessageCreator(parts[2], parts[3], resultsQueue.getName(), msg.getValue().getBytes()));
    }

    // Wait the timeout value per message for all results to be collected
    latch.await((batch.getTimeout() * batch.getMessages().size()), TimeUnit.MINUTES);

    return results;
}

From source file:com.test.sharksharding.util.sequence.GetMysqlSequenceId2Test.java

/**
 * ???SequenceId/*w  w w. j  a  v  a  2s . c  o  m*/
 * 
 * @author gaoxianglong
 */
public @Test void getSequenceId3() {
    final CountDownLatch count = new CountDownLatch(2);
    final List<Long> id1 = new ArrayList<Long>();
    final List<Long> id2 = new ArrayList<Long>();
    final int size = 10000;
    new Thread() {
        public void run() {
            for (int i = 0; i < size; i++) {
                id1.add(SequenceIDManger.getSequenceId(100, 10, 5000));
            }
            count.countDown();
        }
    }.start();
    new Thread() {
        public void run() {
            for (int i = 0; i < size; i++) {
                id2.add(SequenceIDManger.getSequenceId(100, 10, 5000));
            }
            count.countDown();
        }
    }.start();
    try {
        count.await();
        Assert.assertFalse(id1.containsAll(id2));
    } catch (Exception e) {
        e.printStackTrace();
    }
}