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:bundestagswahl.benchmark.BWBenchmark.java

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

    resultTime = new double[6];

    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter URL: ");
    serverUrl = scanner.nextLine();/*from  w  w  w  .j  a  v a  2  s . c o m*/
    System.out.print("Please enter number of terminals: ");
    numberTerminals = scanner.nextInt();
    System.out.print("Please enter number of requests: ");
    numberRequests = scanner.nextInt();
    System.out.print("Please enter delay between two requests in seconds: ");
    requestDelay = scanner.nextDouble();
    scanner.close();

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(numberTerminals);
    HttpClient httpclient = new DefaultHttpClient(cm);
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    try {
        final CountDownLatch latch = new CountDownLatch(numberTerminals);
        for (int i = 0; i < numberTerminals; i++) {
            BenchmarkTerminal terminal = new BenchmarkTerminal(httpclient, latch, serverUrl, numberRequests,
                    requestDelay);
            terminal.start();
        }
        latch.await();
        httpclient.getConnectionManager().shutdown();
    } finally {

    }

    printResultTimes();
    System.out.println(" ");
    System.out.println("Done");
}

From source file:com.ok2c.lightmtp.examples.LocalMailClientTransportExample.java

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

    String text1 = "From: root\r\n" + "To: testuser1\r\n" + "Subject: test message 1\r\n" + "\r\n"
            + "This is a short test message 1\r\n";
    String text2 = "From: root\r\n" + "To: testuser1, testuser2\r\n" + "Subject: test message 2\r\n" + "\r\n"
            + "This is a short test message 2\r\n";
    String text3 = "From: root\r\n" + "To: testuser1, testuser2, testuser3\r\n" + "Subject: test message 3\r\n"
            + "\r\n" + "This is a short test message 3\r\n";

    DeliveryRequest request1 = new BasicDeliveryRequest("root", Arrays.asList("testuser1"),
            new ByteArraySource(text1.getBytes("US-ASCII")));

    DeliveryRequest request2 = new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"),
            new ByteArraySource(text2.getBytes("US-ASCII")));

    DeliveryRequest request3 = new BasicDeliveryRequest("root",
            Arrays.asList("testuser1", "testuser2", "testuser3"),
            new ByteArraySource(text3.getBytes("US-ASCII")));

    Queue<DeliveryRequest> queue = new ConcurrentLinkedQueue<DeliveryRequest>();
    queue.add(request1);//from w w w  . j  av  a2  s  .  co m
    queue.add(request2);
    queue.add(request3);

    CountDownLatch messageCount = new CountDownLatch(queue.size());

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build();

    MailClientTransport mua = new LocalMailClientTransport(config);
    mua.start(new MyDeliveryRequestHandler(messageCount));

    SessionEndpoint endpoint = new SessionEndpoint(new InetSocketAddress("localhost", 2525));

    SessionRequest sessionRequest = mua.connect(endpoint, queue, null);
    sessionRequest.waitFor();

    IOSession iosession = sessionRequest.getSession();
    if (iosession != null) {
        messageCount.await();
    } else {
        IOException ex = sessionRequest.getException();
        if (ex != null) {
            System.out.println("Connection failed: " + ex.getMessage());
        }
    }

    System.out.println("Shutting down I/O reactor");
    try {
        mua.shutdown();
    } catch (IOException ex) {
        mua.forceShutdown();
    }
    System.out.println("Done");
}

From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java

/**
 * The main method./*from www .ja va2s . c om*/
 *
 * @param args
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(String[] args) throws Exception {

    HydrographMain hydrographMain = new HydrographMain();
    final Timer timer = new Timer();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        Session session = null;
        boolean isExecutionTracking = false;
        String[] argsList = args;
        List<String> argumentList = new ArrayList<String>(Arrays.asList(args));
        final String jobId = hydrographMain.getJobId(argumentList);

        getLogLevel(argumentList).ifPresent(x -> {
            if (!x.equalsIgnoreCase(String.valueOf(logger.getLevel()))) {
                setLoglevel(x);
            } else {
                Optional.empty();
            }

        });

        logger.info("Argument List: " + argumentList.toString());

        String trackingClientSocketPort = hydrographMain.getTrackingClientSocketPort(argumentList);

        if (argumentList.contains(Constants.IS_TRACKING_ENABLE)) {
            int index = argumentList.indexOf(Constants.IS_TRACKING_ENABLE);
            isExecutionTracking = Boolean.valueOf(argsList[index + 1]);
            argumentList = removeItemFromIndex(index, argumentList);
        }

        if (argumentList.contains(Constants.TRACKING_CLIENT_SOCKET_PORT)) {
            int index = argumentList.indexOf(Constants.TRACKING_CLIENT_SOCKET_PORT);
            argumentList = removeItemFromIndex(index, argumentList);
        }

        argsList = argumentList.toArray(new String[argumentList.size()]);

        logger.debug("Execution tracking enabled - " + isExecutionTracking);
        logger.info("Tracking Client Port: " + trackingClientSocketPort);

        /**
         * Start new thread to run job
         */
        final HydrographService execution = new HydrographService();

        FutureTask task = hydrographMain.executeGraph(latch, jobId, argsList, execution, isExecutionTracking);

        hydrographMain.executorService = Executors.newSingleThreadExecutor();
        hydrographMain.executorService.submit(task);

        if (isExecutionTracking) {
            //If tracking is enabled, start to post execution tracking status.
            final HydrographEngineCommunicatorSocket socket = new HydrographEngineCommunicatorSocket(execution);
            session = hydrographMain.connectToServer(socket, jobId, trackingClientSocketPort);
            hydrographMain.sendExecutionTrackingStatus(latch, session, jobId, timer, execution, socket);
        }

        //waiting for execute graph thread 
        task.get();

    } catch (Exception exp) {
        logger.info("Getting exception from HydrographMain");
        throw new RuntimeException(exp);
    } finally {
        //cleanup threads --> executor thread and timer thread 
        logger.info("HydrographMain releasing resources");
        if (!hydrographMain.executorService.isShutdown() && !hydrographMain.executorService.isTerminated()) {
            hydrographMain.executorService.shutdown();
        }
        timer.cancel();

    }
}

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.j  a  v a  2  s . c  o  m*/
    }

    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:com.xoom.rabbit.test.Main.java

public static void main(String[] args) throws InterruptedException {
    if (args.length != 9) {
        System.out.println(/*from www . j a v  a2s  .co m*/
                "usage: java -jar target/rabbit-tester-0.1-SNAPSHOT-standalone.jar [consumer_threads] [number_of_messages] [amqp_host] [amqp_port] [produce] [consume] [message size in bytes] [username] [password]");
        return;
    }
    final long startTime = System.currentTimeMillis();
    int consumerThreads = Integer.parseInt(args[0]);
    final int messages = Integer.parseInt(args[1]);
    String host = args[2];
    int port = Integer.parseInt(args[3]);
    boolean produce = Boolean.parseBoolean(args[4]);
    boolean consume = Boolean.parseBoolean(args[5]);
    final int messageSize = Integer.parseInt(args[6]);
    String username = args[7];
    String password = args[8];

    if (produce) {
        System.out.println("Sending " + messages + " messages to " + host + ":" + port);
    }
    if (consume) {
        System.out.println("Consuming " + messages + " messages from " + host + ":" + port);
    }
    if (!produce && !consume) {
        System.out.println("Not producing or consuming any messages.");
    }

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setChannelCacheSize(consumerThreads + 1);

    RabbitAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

    DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false);
    Queue queue = new Queue(QUEUE_NAME);
    amqpAdmin.declareExchange(exchange);
    amqpAdmin.declareQueue(queue);
    amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY));

    final AmqpTemplate amqpTemplate = new RabbitTemplate(connectionFactory);

    final CountDownLatch producerLatch = new CountDownLatch(messages);
    final CountDownLatch consumerLatch = new CountDownLatch(messages);

    SimpleMessageListenerContainer listenerContainer = null;

    if (consume) {
        listenerContainer = new SimpleMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setQueueNames(QUEUE_NAME);
        listenerContainer.setConcurrentConsumers(consumerThreads);
        listenerContainer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (consumerLatch.getCount() == 1) {
                    System.out.println("Finished consuming " + messages + " messages in "
                            + (System.currentTimeMillis() - startTime) + "ms");
                }
                consumerLatch.countDown();
            }
        });
        listenerContainer.start();
    }

    if (produce) {
        while (producerLatch.getCount() > 0) {
            try {
                byte[] message = new byte[messageSize];
                RND.nextBytes(message);
                amqpTemplate.send(EXCHANGE_NAME, ROUTING_KEY, new Message(message, new MessageProperties()));
                producerLatch.countDown();
            } catch (Exception e) {
                System.out.println("Failed to send message " + (messages - producerLatch.getCount())
                        + " will retry forever.");
            }
        }
    }

    if (consume) {
        consumerLatch.await();
        listenerContainer.shutdown();
    }

    connectionFactory.destroy();
}

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

/**
 * Main program entry point./* w w w .  j  av a2s.co  m*/
 * @param args command-line arguments
 * @throws Exception in case of any errors
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        printUsage();

        return;
    }

    ActorSystem actorSystem = ActorSystem.create("Proxy", ConfigFactory.load().getConfig("proxy"));
    SignerClient.init(actorSystem);

    Thread.sleep(SIGNER_INIT_DELAY); // wait for signer client to connect

    BatchSigner.init(actorSystem);

    X509Certificate subjectCert = TestCertUtil.getConsumer().cert;
    X509Certificate issuerCert = TestCertUtil.getCaCert();
    X509Certificate signerCert = TestCertUtil.getOcspSigner().cert;
    PrivateKey signerKey = TestCertUtil.getOcspSigner().key;

    List<String> messages = new ArrayList<>();

    for (String arg : args) {
        messages.add(FileUtils.readFileToString(new File(arg)));
    }

    latch = new CountDownLatch(messages.size());

    Date thisUpdate = new DateTime().plusDays(1).toDate();
    final OCSPResp ocsp = OcspTestUtils.createOCSPResponse(subjectCert, issuerCert, signerCert, signerKey,
            CertificateStatus.GOOD, thisUpdate, null);

    for (final String message : messages) {
        new Thread(() -> {
            try {
                byte[] hash = hash(message);
                log.info("File: {}, hash: {}", message, hash);

                MessagePart hashPart = new MessagePart(MessageFileNames.MESSAGE, SHA512_ID,
                        calculateDigest(SHA512_ID, message.getBytes()), message.getBytes());

                List<MessagePart> hashes = Collections.singletonList(hashPart);

                SignatureBuilder builder = new SignatureBuilder();
                builder.addPart(hashPart);

                builder.setSigningCert(subjectCert);
                builder.addOcspResponses(Collections.singletonList(ocsp));

                log.info("### Calculating signature...");

                SignatureData signatureData = builder.build(
                        new SignerSigningKey(KEY_ID, CryptoUtils.CKM_RSA_PKCS_NAME), CryptoUtils.SHA512_ID);

                synchronized (sigIdx) {
                    log.info("### Created signature: {}", signatureData.getSignatureXml());

                    log.info("HashChainResult: {}", signatureData.getHashChainResult());
                    log.info("HashChain: {}", signatureData.getHashChain());

                    toFile("message-" + sigIdx + ".xml", message);

                    String sigFileName = signatureData.getHashChainResult() != null ? "batch-sig-" : "sig-";

                    toFile(sigFileName + sigIdx + ".xml", signatureData.getSignatureXml());

                    if (signatureData.getHashChainResult() != null) {
                        toFile("hash-chain-" + sigIdx + ".xml", signatureData.getHashChain());
                        toFile("hash-chain-result.xml", signatureData.getHashChainResult());
                    }

                    sigIdx++;
                }

                try {
                    verify(signatureData, hashes, message);

                    log.info("Verification successful (message hash: {})", hash);
                } catch (Exception e) {
                    log.error("Verification failed (message hash: {})", hash, e);
                }
            } catch (Exception e) {
                log.error("Error", e);
            } finally {
                latch.countDown();
            }
        }).start();
    }

    latch.await();
    actorSystem.shutdown();
}

From source file:org.eclipse.ecf.provider.filetransfer.httpcore.NHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    //CountDownLatch requestCount = new CountDownLatch(3);
    CountDownLatch requestCount = new CountDownLatch(1);

    BufferingHttpClientHandler handler = new MyBufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }/*  w w w  . jav  a 2s .c o  m*/
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[1];
    reqs[0] = ioReactor.connect(new InetSocketAddress("ftp.osuosl.org", 80), null,
            new HttpHost("ftp.osuosl.org"), new MySessionRequestCallback(requestCount));
    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:NHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    CountDownLatch requestCount = new CountDownLatch(3);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//w ww  . ja  va  2  s .  com
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[3];
    reqs[0] = ioReactor.connect(new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"),
            new MySessionRequestCallback(requestCount));
    reqs[1] = ioReactor.connect(new InetSocketAddress("www.google.com", 80), null,
            new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount));
    reqs[2] = ioReactor.connect(new InetSocketAddress("www.apache.org", 80), null,
            new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount));

    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

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);/*from w w  w. jav a  2s  .c  om*/
    // 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");

}

From source file:framework.httpclient.nio.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("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true))
            .build();//w  w  w. j  av a 2 s .c om

    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();

    // Create client-side I/O event dispatch
    //   IO 
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);

    // Create client-side I/O reactor
    //   IO reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();

    // Create HTTP connection pool
    //  HTTP 
    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
    //  HTTP 
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);

    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"),
            //            new HttpHost("www.zhihu.com", -1, "https"),
            new HttpHost("www.bilibili.com", -1, "https") };

    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.err.println(target + "->" + ex);
                        ex.printStackTrace();
                    }

                    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");
}