Example usage for java.nio.channels AsynchronousChannelGroup awaitTermination

List of usage examples for java.nio.channels AsynchronousChannelGroup awaitTermination

Introduction

In this page you can find the example usage for java.nio.channels AsynchronousChannelGroup awaitTermination.

Prototype

public abstract boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Awaits termination of the group.

Usage

From source file:async.nio2.Main.java

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

    if (args.length == 3) {
        PORT = Integer.valueOf(args[0]);
        NO_CLIENTS = Integer.valueOf(args[1]);
        NO_SAMPLES = Integer.valueOf(args[2]);
    }// w  w  w  .j  a  v a  2  s . c om

    if (PORT < 0) {
        System.err.println("Error: port < 0");
        System.exit(1);
    }

    if (NO_CLIENTS < 1) {
        System.err.println("Error: #clients < 1");
        System.exit(1);
    }

    if (NO_SAMPLES < 1) {
        System.err.println("Error: #samples < 1");
        System.exit(1);
    }

    AsynchronousChannelGroup groupServer = AsynchronousChannelGroup
            .withThreadPool(Executors.newFixedThreadPool(1));
    AsynchronousChannelGroup groupClient = AsynchronousChannelGroup
            .withThreadPool(Executors.newFixedThreadPool(1));

    Server server = Server.newInstance(new InetSocketAddress("localhost", PORT), groupServer);
    InetSocketAddress localAddress = server.getLocalAddress();
    String hostname = localAddress.getHostName();
    int port = localAddress.getPort();

    ExecutorService es = Executors.newFixedThreadPool(2);

    System.out.printf("%03d clients on %s:%d, %03d runs each. All times in s.%n", NO_CLIENTS, hostname, port,
            NO_SAMPLES);
    range(0, NO_CLIENTS).unordered().parallel()
            .mapToObj(i -> CompletableFuture.supplyAsync(newClient(localAddress, groupClient), es).join())
            .map(array -> Arrays.stream(array).reduce(new DescriptiveStatistics(), Main::accumulate,
                    Main::combine))
            .map(Main::toEvaluationString).forEach(System.out::println);

    es.shutdown();
    es.awaitTermination(5, TimeUnit.SECONDS);

    groupClient.shutdown();
    groupClient.awaitTermination(5, TimeUnit.SECONDS);

    server.close();
    groupServer.shutdown();
    groupServer.awaitTermination(5, TimeUnit.SECONDS);
}