Example usage for io.netty.channel.nio NioEventLoopGroup shutdownGracefully

List of usage examples for io.netty.channel.nio NioEventLoopGroup shutdownGracefully

Introduction

In this page you can find the example usage for io.netty.channel.nio NioEventLoopGroup shutdownGracefully.

Prototype

@Override
    public Future<?> shutdownGracefully() 

Source Link

Usage

From source file:org.opendaylight.netconf.test.tool.client.stress.StressClient.java

License:Open Source License

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

    params = parseArgs(args, Parameters.getParser());
    params.validate();/*from   ww  w .  java2s.co  m*/

    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(params.debug ? Level.DEBUG : Level.INFO);

    final int threadAmount = params.threadAmount;
    LOG.info("thread amount: " + threadAmount);
    final int requestsPerThread = params.editCount / params.threadAmount;
    LOG.info("requestsPerThread: " + requestsPerThread);
    final int leftoverRequests = params.editCount % params.threadAmount;
    LOG.info("leftoverRequests: " + leftoverRequests);

    LOG.info("Preparing messages");
    // Prepare all msgs up front
    final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
    for (int i = 0; i < threadAmount; i++) {
        if (i != threadAmount - 1) {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
        } else {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
        }
    }

    final String editContentString;
    try {
        editContentString = Files.toString(params.editContent, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot read content of " + params.editContent);
    }

    for (int i = 0; i < threadAmount; i++) {
        final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
        int padding = 0;
        if (i == threadAmount - 1) {
            padding = leftoverRequests;
        }
        for (int j = 0; j < requestsPerThread + padding; j++) {
            LOG.debug("id: " + (i * requestsPerThread + j));
            preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
        }
    }

    final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
    final Timer timer = new HashedWheelTimer();

    final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup,
            timer);

    final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
    for (final List<NetconfMessage> messages : allPreparedMessages) {
        callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);

    LOG.info("Starting stress test");
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Boolean>> futures = executorService.invokeAll(callables);
        for (final Future<Boolean> future : futures) {
            try {
                future.get(4L, TimeUnit.MINUTES);
            } catch (ExecutionException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.shutdownNow();
    } catch (final InterruptedException e) {
        throw new RuntimeException("Unable to execute requests", e);
    }
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));

    // Cleanup
    timer.stop();
    try {
        nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        LOG.warn("Unable to close executor properly", e);
    }
    //stop the underlying ssh thread that gets spawned if we use ssh
    if (params.ssh) {
        AsyncSshHandler.DEFAULT_CLIENT.stop();
    }
}

From source file:org.robotninjas.barge.RaftModule.java

License:Apache License

@Override
protected void configure() {

    install(new StateModule(timeout));
    Replica local = config.local();/*www .j av a 2s . co m*/

    final NioEventLoopGroup eventLoop;
    if (eventLoopGroup.isPresent()) {
        eventLoop = eventLoopGroup.get();
    } else {
        eventLoop = new NioEventLoopGroup();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                eventLoop.shutdownGracefully();
            }
        });
    }
    install(new RpcModule(local.address(), eventLoop));

    final ListeningExecutorService executor;
    if (stateMachineExecutor.isPresent()) {
        executor = stateMachineExecutor.get();
    } else {
        executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                executor.shutdownNow();
            }
        });
    }
    install(new LogModule(logDir, stateMachine, executor));

    bind(ClusterConfig.class).toInstance(config);

    bind(RaftService.class);
    expose(RaftService.class);

}

From source file:org.wildfly.camel.test.lumberjack.LumberjackComponentTest.java

License:Apache License

private List<Integer> sendMessages(int port, SSLContextParameters sslContextParameters)
        throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {//from  w ww  .jav a  2 s .c  o m
        // This list will hold the acknowledgment response sequence numbers
        List<Integer> responses = new ArrayList<>();

        // This initializer configures the SSL and an acknowledgment recorder
        ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (sslContextParameters != null) {
                    SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
                    sslEngine.setUseClientMode(true);
                    pipeline.addLast(new SslHandler(sslEngine));
                }

                // Add the response recorder
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        Assert.assertEquals(msg.readUnsignedByte(), (short) '2');
                        Assert.assertEquals(msg.readUnsignedByte(), (short) 'A');
                        synchronized (responses) {
                            responses.add(msg.readInt());
                        }
                    }
                });
            }
        };

        // Connect to the server
        Channel channel = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(initializer).connect("127.0.0.1", port).sync().channel();

        // Send the 2 window frames
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("lumberjack/window10"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("lumberjack/window15"));
        TimeUnit.MILLISECONDS.sleep(100);

        channel.close();

        synchronized (responses) {
            return responses;
        }
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}

From source file:tk.jomp16.utils.Utils.java

License:Open Source License

public static void downloadDccFileStream(File f, String ip, int port, long bytes, long startPosition)
        throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    try {//from www .  java 2 s  . co  m
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DccFileSendNettyDecoder(f, startPosition),
                        new DccFileSendNettyEncoder());
            }
        });
        bootstrap.connect(ip, port).sync().channel().closeFuture().sync();
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}