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 boolean await(long timeout, TimeUnit unit) 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 , or the specified waiting time elapses.

Usage

From source file:Main.java

public static void main(String args[]) {
    CountDownLatch cdl = new CountDownLatch(5);
    System.out.println(cdl.getCount());
    new MyThread(cdl);

    try {/*from  w  w w  .  j  ava  2 s. c  om*/
        cdl.await(100, TimeUnit.SECONDS);
    } catch (InterruptedException exc) {
        System.out.println(exc);
    }
    System.out.println("Done");
}

From source file:Main.java

public static void main(String args[]) {
    CountDownLatch cdl = new CountDownLatch(5);
    System.out.println(cdl.getCount());
    new MyThread(cdl);

    try {/*w  w  w.  j  av a2s  .  c o  m*/
        cdl.await(100, TimeUnit.SECONDS);
    } catch (InterruptedException exc) {
        System.out.println(exc);
    }
    System.out.println(cdl.toString());
}

From source file:ch.rasc.wampspring.demo.client.Publisher.java

public static void main(String[] args) throws InterruptedException {

    WebSocketClient webSocketClient = new StandardWebSocketClient();
    final JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());

    final CountDownLatch welcomeLatch = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(1_000_000);
    TextWebSocketHandler handler = new TextWebSocketHandler() {

        @Override//from   w  ww .java  2  s .  com
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            WampMessage wampMessage = WampMessage.fromJson(jsonFactory, message.getPayload());

            if (wampMessage instanceof WelcomeMessage) {
                latch.countDown();
            }

        }

    };

    Long[] start = new Long[1];
    ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler,
            "ws://localhost:8080/wamp");
    future.addCallback(wss -> {

        // Waiting for WELCOME message
        try {
            welcomeLatch.await(5, TimeUnit.SECONDS);

            start[0] = System.currentTimeMillis();
            for (int i = 0; i < 1_000_000; i++) {
                PublishMessage publishMessage = new PublishMessage("/test/myqueue", i);
                try {
                    wss.sendMessage(new TextMessage(publishMessage.toJson(jsonFactory)));
                } catch (Exception e) {
                    System.out.println("ERROR SENDING PUBLISH_MESSAGE" + e);
                }
                latch.countDown();
            }

        } catch (Exception e1) {
            System.out.println("SENDING PUBLISH MESSAGES: " + e1);
        }

    }, t -> {
        System.out.println("DO HANDSHAKE ERROR: " + t);
        System.exit(1);
    });

    if (!latch.await(3, TimeUnit.MINUTES)) {
        System.out.println("SOMETHING WENT WRONG");
    }
    System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds");
}

From source file:ch.rasc.wampspring.demo.client.CallClient.java

public static void main(String[] args) throws InterruptedException {
    WebSocketClient webSocketClient = new StandardWebSocketClient();
    JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());

    CountDownLatch latch = new CountDownLatch(1_000_000);
    TestTextWebSocketHandler handler = new TestTextWebSocketHandler(jsonFactory, latch);

    Long[] start = new Long[1];
    ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler,
            "ws://localhost:8080/wamp");
    future.addCallback(wss -> {//ww  w .  j a v  a2  s  .  c  o m
        start[0] = System.currentTimeMillis();
        for (int i = 0; i < 1_000_000; i++) {

            CallMessage callMessage = new CallMessage(UUID.randomUUID().toString(), "testService.sum", i,
                    i + 1);
            try {
                wss.sendMessage(new TextMessage(callMessage.toJson(jsonFactory)));
            } catch (Exception e) {
                System.out.println("ERROR SENDING CALLMESSAGE" + e);
                latch.countDown();
            }
        }

    }, t -> {
        System.out.println("DO HANDSHAKE ERROR: " + t);
        System.exit(1);
    });

    if (!latch.await(3, TimeUnit.MINUTES)) {
        System.out.println("SOMETHING WENT WRONG");
    }

    System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds");
    System.out.println("SUCCESS: " + handler.getSuccess());
    System.out.println("ERROR  : " + handler.getError());
}

From source file:ch.rasc.wampspring.demo.client.CallClientSockJs.java

public static void main(String[] args) throws InterruptedException {

    List<Transport> transports = new ArrayList<>(2);
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    transports.add(new RestTemplateXhrTransport());
    WebSocketClient webSocketClient = new SockJsClient(transports);

    JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());

    CountDownLatch latch = new CountDownLatch(10_000);
    TestTextWebSocketHandler handler = new TestTextWebSocketHandler(jsonFactory, latch);

    Long[] start = new Long[1];
    ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler,
            "ws://localhost:8080/wampOverSockJS");
    future.addCallback(wss -> {//from w  ww  . j a  va2 s  . c  o m
        start[0] = System.currentTimeMillis();
        for (int i = 0; i < 10_000; i++) {

            CallMessage callMessage = new CallMessage(UUID.randomUUID().toString(), "testService.sum", i,
                    i + 1);
            try {
                wss.sendMessage(new TextMessage(callMessage.toJson(jsonFactory)));
            } catch (Exception e) {
                System.out.println("ERROR SENDING CALLMESSAGE" + e);
                latch.countDown();
            }
        }

    }, t -> {
        System.out.println("DO HANDSHAKE ERROR: " + t);
        System.exit(1);
    });

    if (!latch.await(3, TimeUnit.MINUTES)) {
        System.out.println("SOMETHING WENT WRONG");
    }

    System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds");
    System.out.println("SUCCESS: " + handler.getSuccess());
    System.out.println("ERROR  : " + handler.getError());
}

From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];// w  w  w.  jav  a2 s  .  com
    }

    int port = 59984;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String url = "http://" + host + ":" + port + "/home";
    logger.debug("Sending warm-up HTTP request to " + url);
    HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor);
    JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient);
    webSocketClient.start();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        URI uri = new URI("ws://" + host + ":" + port + "/stomp");
        WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompMessageHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(consumers.get(i));
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(producer);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompMessageHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        webSocketClient.stop();
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:Main.java

public static void await(CountDownLatch barrier, long timeoutMillis) {
    try {/* w  w  w.  j a  v a 2s  .  c o  m*/
        barrier.await(timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:Main.java

public static void await(CountDownLatch latch, int timeout) {
    try {/*from www .j  av  a2s  .  c o  m*/
        latch.await(timeout, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // Meh
    }
}

From source file:Main.java

public static boolean await(CountDownLatch cl, long millseconds) {
    try {/*from ww w. j a va 2s  .  com*/
        return cl.await(millseconds, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        return false;
    }
}

From source file:io.dropwizard.websockets.DropWizardWebsocketsTest.java

@BeforeClass
public static void setUpClass() throws InterruptedException, IOException {
    CountDownLatch serverStarted = new CountDownLatch(1);
    Thread serverThread = new Thread(GeneralUtils.rethrow(() -> new MyApp(serverStarted)
            .run(new String[] { "server", Resources.getResource("server.yml").getPath() })));
    serverThread.setDaemon(true);/*  ww  w .java  2  s. com*/
    serverThread.start();
    serverStarted.await(10, SECONDS);
}