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.example.AsyncClientHttpExchangeFutureCallback.java

public static void main(String[] args) throws Exception {
    HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    httpclient.start();//from  ww w.  j  a  v  a2 s.co  m
    try {
        HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"),
                new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") };
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (final HttpGet request : requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
    } finally {
        httpclient.shutdown();
    }
    System.out.println("Done");
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientHttpExchangeFutureCallback.java

public static void main(final String[] args) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .build();/*from  w  w  w. j a  v  a  2  s. c  o  m*/
    try {
        httpclient.start();
        final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"),
                new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") };
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (final HttpGet request : requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:rg.apache.http.examples.async.AsyncClientHttpExchangeFutureCallback.java

public static void main(final String[] args) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .setThreadFactory(new NamedThreadFactory("dddddddd")).build();
    try {/*from  w w  w  . j  a  v  a 2 s. co m*/
        httpclient.start();
        final HttpGet[] requests = new HttpGet[] { new HttpGet("http://httpbin.org/ip"),
                new HttpGet("https://httpbin.org/ip"), new HttpGet("http://httpbin.org/headers") };
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (final HttpGet request : requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:io.pivotal.ListApplicationsApplication.java

public static void main(String[] args) throws InterruptedException {
    ConfigurableApplicationContext applicationContext = SpringApplication.run(ListApplicationsApplication.class,
            args);/*ww w  . ja v a  2 s  . co  m*/
    CloudFoundryClient cloudFoundryClient = applicationContext.getBean(CloudFoundryClient.class);
    CloudFoundryOperations cloudFoundryOperations = applicationContext.getBean(CloudFoundryOperations.class);

    CountDownLatch latch = new CountDownLatch(1);

    cloudFoundryOperations.applications().list().flatMap(
            application -> Mono.just(application).and(getServiceInstances(cloudFoundryClient, application)))
            .map(function(FormattingUtils::formatApplication)).subscribe(System.out::println, t -> {
                t.printStackTrace();
                latch.countDown();
            }, latch::countDown);

    latch.await();
}

From source file:httpasync.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//from w w  w . j  av  a2s .  com
        // Start the client
        httpclient.start();

        // Execute request
        final HttpGet request1 = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request1, null);
        // and wait until response is received
        HttpResponse response1 = future.get();
        System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine());

        // One most likely would want to use a callback for operation result
        final CountDownLatch latch1 = new CountDownLatch(1);
        final HttpGet request2 = new HttpGet("http://www.apache.org/");
        httpclient.execute(request2, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response2) {
                latch1.countDown();
                System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine());
            }

            @Override
            public void failed(final Exception ex) {
                latch1.countDown();
                System.out.println(request2.getRequestLine() + "->" + ex);
            }

            @Override
            public void cancelled() {
                latch1.countDown();
                System.out.println(request2.getRequestLine() + " cancelled");
            }

        });
        latch1.await();

        // In real world one most likely would want also want to stream
        // request and response body content
        final CountDownLatch latch2 = new CountDownLatch(1);
        final HttpGet request3 = new HttpGet("http://www.apache.org/");
        HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3);
        AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() {

            HttpResponse response;

            @Override
            protected void onResponseReceived(final HttpResponse response) {
                this.response = response;
            }

            @Override
            protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
                // Do something useful
            }

            @Override
            protected void releaseResources() {
            }

            @Override
            protected HttpResponse buildResult(final HttpContext context) {
                return this.response;
            }

        };
        httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response3) {
                latch2.countDown();
                System.out.println(request2.getRequestLine() + "->" + response3.getStatusLine());
            }

            @Override
            public void failed(final Exception ex) {
                latch2.countDown();
                System.out.println(request2.getRequestLine() + "->" + ex);
            }

            @Override
            public void cancelled() {
                latch2.countDown();
                System.out.println(request2.getRequestLine() + " cancelled");
            }

        });
        latch2.await();

    } finally {
        httpclient.close();
    }
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
    cm.setMaxTotal(100);// www.  ja  v  a2s.co m
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(cm).build();
    try {
        httpclient.start();

        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/",
                "http://hc.apache.org/httpcomponents-client-ga/", };

        IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
        connEvictor.start();

        final CountDownLatch latch = new CountDownLatch(urisToGet.length);
        for (final String uri : urisToGet) {
            final HttpGet httpget = new HttpGet(uri);
            httpclient.execute(httpget, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(httpget.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(httpget.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(httpget.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();

        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(20000);

        // Shut down the evictor thread
        connEvictor.shutdown();
        connEvictor.join();

    } finally {
        httpclient.close();
    }
}

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 w w.  ja va  2 s .  c  o  m
        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:com.github.ambry.store.DiskReformatter.java

public static void main(String[] args) throws Exception {
    VerifiableProperties properties = ToolUtils.getVerifiableProperties(args);
    DiskReformatterConfig config = new DiskReformatterConfig(properties);
    StoreConfig storeConfig = new StoreConfig(properties);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties);
    ServerConfig serverConfig = new ServerConfig(properties);
    ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory,
            clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath);
    try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) {
        StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj(
                serverConfig.serverStoreKeyConverterFactory, properties, clusterMap.getMetricRegistry());
        StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap);
        DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort);
        if (dataNodeId == null) {
            throw new IllegalArgumentException("Did not find node in clustermap with hostname:port - "
                    + config.datanodeHostname + ":" + config.datanodePort);
        }//w  w  w  . jav a 2 s  . c o  m
        DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST,
                config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance(),
                storeKeyConverterFactory.getStoreKeyConverter());
        AtomicInteger exitStatus = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length);
        for (int i = 0; i < config.diskMountPaths.length; i++) {
            int finalI = i;
            Runnable runnable = () -> {
                try {
                    reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI]));
                    latch.countDown();
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            };
            Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true);
            thread.setUncaughtExceptionHandler((t, e) -> {
                exitStatus.set(1);
                logger.error("Reformatting {} failed", config.diskMountPaths[finalI], e);
                latch.countDown();
            });
            thread.start();
        }
        latch.await();
        System.exit(exitStatus.get());
    }
}

From source file:com.twitter.distributedlog.basic.MultiReader.java

public static void main(String[] args) throws Exception {
    if (2 != args.length) {
        System.out.println(HELP);
        return;//from  ww  w  .  j  av  a 2 s .  c o m
    }

    String dlUriStr = args[0];
    final String streamList = args[1];

    URI uri = URI.create(dlUriStr);
    DistributedLogConfiguration conf = new DistributedLogConfiguration();
    DistributedLogNamespace namespace = DistributedLogNamespaceBuilder.newBuilder().conf(conf).uri(uri).build();

    String[] streamNameList = StringUtils.split(streamList, ',');
    DistributedLogManager[] managers = new DistributedLogManager[streamNameList.length];

    for (int i = 0; i < managers.length; i++) {
        String streamName = streamNameList[i];
        // open the dlm
        System.out.println("Opening log stream " + streamName);
        managers[i] = namespace.openLog(streamName);
    }

    final CountDownLatch keepAliveLatch = new CountDownLatch(1);

    for (DistributedLogManager dlm : managers) {
        final DistributedLogManager manager = dlm;
        dlm.getLastLogRecordAsync().addEventListener(new FutureEventListener<LogRecordWithDLSN>() {
            @Override
            public void onFailure(Throwable cause) {
                if (cause instanceof LogNotFoundException) {
                    System.err.println(
                            "Log stream " + manager.getStreamName() + " is not found. Please create it first.");
                    keepAliveLatch.countDown();
                } else if (cause instanceof LogEmptyException) {
                    System.err.println("Log stream " + manager.getStreamName() + " is empty.");
                    readLoop(manager, DLSN.InitialDLSN, keepAliveLatch);
                } else {
                    System.err.println("Encountered exception on process stream " + manager.getStreamName());
                    keepAliveLatch.countDown();
                }
            }

            @Override
            public void onSuccess(LogRecordWithDLSN record) {
                readLoop(manager, record.getDlsn(), keepAliveLatch);
            }
        });
    }
    keepAliveLatch.await();
    for (DistributedLogManager dlm : managers) {
        dlm.close();
    }
    namespace.close();
}

From source file:com.yulore.demo.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("Test/1.1")).add(new RequestExpectContinue(true)).build();
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);/* www .  j  a  v a 2s.  c o  m*/
    // Create client-side I/O reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);
    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.apache.org", 80, "http"),
            new HttpHost("www.verisign.com", 443, "https"), new HttpHost("www.google.com", 80, "http") };
    final CountDownLatch latch = new CountDownLatch(targets.length);
    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.out.println(target + "->" + ex);
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");

}