Example usage for java.nio.channels AsynchronousChannelGroup shutdown

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

Introduction

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

Prototype

public abstract void shutdown();

Source Link

Document

Initiates an orderly shutdown 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]);
    }/*ww w  . j a  va2s.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);
}

From source file:net.transmutator4j.RunTransmutator4j.java

@Override
public void run() {

    long startTime = System.currentTimeMillis();
    InetAddress localhost;/*from www  . ja  v a2 s  .  c  om*/
    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new IllegalStateException("can not resolve local host", e);
    }
    //socket get dynamically generated port
    SocketAddress socket = new InetSocketAddress(localhost, 0);
    AsynchronousChannelGroup group;
    try {
        group = AsynchronousChannelGroup.withFixedThreadPool(10, Executors.defaultThreadFactory());
    } catch (IOException e1) {
        throw new IllegalStateException("can not create channel group", e1);
    }

    try (

            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(socket,
                    1);

    ) {

        int numTotalTests = runUnmutatedTests();
        long unmutatedTimeEnd = System.currentTimeMillis();
        long unmutatedElapsedTime = unmutatedTimeEnd - startTime;
        listener.testInfo(numTotalTests, unmutatedElapsedTime);
        System.out.println("unmutated tests took " + unmutatedElapsedTime + " ms");
        long timeOut = computeTimeoutTime(unmutatedElapsedTime);
        InetSocketAddress inetSocketAddress = (InetSocketAddress) server.getLocalAddress();
        int port = inetSocketAddress.getPort();
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel resultChannel, Object attachment) {
                try {
                    ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(resultChannel));
                    MutationTestResult testResult = (MutationTestResult) in.readObject();

                    in.close();

                    listener.mutationResult(testResult);
                    boolean stillPassed = testResult.testsStillPassed();
                    System.out.print(stillPassed ? "P" : ".");
                    System.out.flush();
                    numberOfMutationsMade++;

                    if (stillPassed) {
                        numberOfMutationsThatStillPassedTests++;
                    }
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new RuntimeException("error getting test result ", e);
                }
                //accept a new connection
                server.accept(null, this);

            }

            @Override
            public void failed(Throwable e, Object attachment) {
                //   System.err.println(attachment + " failed with:" + e.getClass().getName());
                //    e.printStackTrace();
            }
        });

        OUTER: for (String classToMutate : new ClassPathClassRepository()) {
            boolean shouldMutate = shouldMutate(classToMutate);
            if (shouldMutate) {
                System.out.printf("mutating %s%n", classToMutate);
                boolean done = false;
                int mutationCount = 0;
                while (!done) {
                    JavaProcessBuilder builder = new JavaProcessBuilder(

                            "net.transmutator4j.Transmutator4j", classToMutate, nameOfTestSuite,
                            Integer.toString(mutationCount), Integer.toString(port));

                    try {
                        TimedProcess timedProcess = new TimedProcess(builder.getBuilder(), timeOut);
                        int exitValue = timedProcess.call();

                        TransmutatorUtil.EXIT_STATES exitState = TransmutatorUtil.EXIT_STATES
                                .getValueFor(exitValue);
                        if (exitState == TransmutatorUtil.EXIT_STATES.NO_MUTATIONS_MADE) {
                            done = true;
                            System.out.println();
                        } else if (exitState == TransmutatorUtil.EXIT_STATES.TIMED_OUT) {
                            numberOfMutationsThatTimedOut++;

                        }

                    } catch (InterruptedException e) {
                        System.err.println("detected cancellation...halting");
                        //stop iterating through all the classes
                        //by breaking out of outer for loop
                        break OUTER;
                    }

                    mutationCount++;

                }

            }
        }
        //kill any waiting connections this will cause the completionHandler's fail to get called
        group.shutdownNow();
        //group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

        long endTime = System.currentTimeMillis();
        System.out.printf("took %d ms to run %d mutations of which %d caused timeouts and %d still passed%n",
                (endTime - startTime), numberOfMutationsMade, numberOfMutationsThatTimedOut,
                numberOfMutationsThatStillPassedTests);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (listener != null) {
            try {
                listener.close();
            } catch (IOException ignored) {
                //ignore
            }
        }
        group.shutdown();
    }
}