List of usage examples for io.netty.channel.nio NioEventLoopGroup shutdownGracefully
@Override
public Future<?> shutdownGracefully()
From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java
License:Open Source License
/** * Wraps given {@link ChannelFuture} to ensure the event loops * shut down gracefully./*from w w w.j av a2 s .com*/ * @param target the original channel future. * @param bossGroup the boss group. * @param workerGroup the worker group. * @return the wrapped future. */ @NotNull protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup, @NotNull final NioEventLoopGroup workerGroup) { return new ChannelFuture() { @Override public Channel channel() { return target.channel(); } /** * {@inheritDoc} */ @Override public ChannelFuture addListener( @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) { return target.addListener(listener); } /** * {@inheritDoc} */ @Override public ChannelFuture addListeners( @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) { return target.addListeners(listeners); } /** * {@inheritDoc} */ @Override public ChannelFuture removeListener( @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) { return target.removeListener(listener); } /** * {@inheritDoc} */ @Override public ChannelFuture removeListeners( @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) { return target.removeListeners(listeners); } /** * {@inheritDoc} */ @Override public ChannelFuture sync() throws InterruptedException { ChannelFuture result = null; try { result = target.sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } return result; } /** * {@inheritDoc} */ @Override public ChannelFuture syncUninterruptibly() { return target.syncUninterruptibly(); } /** * {@inheritDoc} */ @Override public ChannelFuture await() throws InterruptedException { return target.await(); } /** * {@inheritDoc} */ @Override public ChannelFuture awaitUninterruptibly() { return target.awaitUninterruptibly(); } /** * {@inheritDoc} */ @Override public boolean isSuccess() { return target.isSuccess(); } /** * {@inheritDoc} */ @Override public boolean isCancellable() { return target.isCancellable(); } /** * {@inheritDoc} */ @Override public Throwable cause() { return target.cause(); } /** * {@inheritDoc} */ @Override public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException { return target.await(timeout, unit); } /** * {@inheritDoc} */ @Override public boolean await(final long timeoutMillis) throws InterruptedException { return target.await(timeoutMillis); } /** * {@inheritDoc} */ @Override public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) { return target.awaitUninterruptibly(timeout, unit); } /** * {@inheritDoc} */ @Override public boolean awaitUninterruptibly(final long timeoutMillis) { return target.awaitUninterruptibly(timeoutMillis); } /** * {@inheritDoc} */ @Override public Void getNow() { return target.getNow(); } /** * {@inheritDoc} */ @Override public boolean cancel(final boolean mayInterruptIfRunning) { return target.cancel(mayInterruptIfRunning); } /** * {@inheritDoc} */ @Override public boolean isCancelled() { return target.isCancelled(); } /** * {@inheritDoc} */ @Override public boolean isDone() { return target.isDone(); } /** * {@inheritDoc} */ @Override public Void get() throws InterruptedException, ExecutionException { return target.get(); } /** * {@inheritDoc} */ @Override public Void get(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return target.get(timeout, unit); } }; }
From source file:org.aotorrent.tracker.TorrentTracker.java
License:Apache License
@Override public void run() { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try {// w w w.j a v a2 s . c o m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new TrackerChannelInitializer(torrents)); // Start the server. ChannelFuture f = b.bind(localSocketAddress.getPort()).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } catch (InterruptedException e) { LOGGER.error("Interrupted", e); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:org.apache.pulsar.discovery.service.DiscoveryServiceTest.java
License:Apache License
@Test public void testClientServerConnectionTls() throws Exception { addBrokerToZk(2);/*from w w w .j ava 2s . co m*/ // 1. client connects to DiscoveryService, 2. Client receive service-lookup response final int messageTransfer = 2; final CountDownLatch latch = new CountDownLatch(messageTransfer); NioEventLoopGroup workerGroup = connectToService(service.getServiceUrlTls(), latch, true); try { assertTrue(latch.await(1, TimeUnit.SECONDS)); } catch (InterruptedException e) { fail("should have received lookup response message from server", e); } workerGroup.shutdownGracefully(); }
From source file:org.asterisque.netty.Netty.java
License:Apache License
/** * *//*from w w w . ja va2s . c o m*/ private NioEventLoopGroup worker() { if (closing.get()) { throw new IllegalStateException("netty bridge already closed"); } if (worker.get() == null) { NioEventLoopGroup w = new NioEventLoopGroup(); if (!worker.compareAndSet(null, w)) { w.shutdownGracefully(); } else { logger.debug("worker NioEventLoop created"); } } return worker.get(); }
From source file:org.asterisque.netty.Netty.java
License:Apache License
/** * ??????????//from w w w . jav a2 s . com * * @return Server ? Future */ public CompletableFuture<Server> newServer(Node node, SocketAddress address, Options options, Consumer<Wire> onAccept) { NioEventLoopGroup master = new NioEventLoopGroup(); // ?????? ServerBootstrap server = new ServerBootstrap(); CompletableFuture<Server> future = new CompletableFuture<>(); Initializer factory = new Initializer(node, true, options, wire -> { logger.debug(Asterisque.logPrefix(true) + ": onAccept(" + wire + ")"); onAccept.accept(wire); }); server.group(master, worker()).channel(NioServerSocketChannel.class).localAddress(address) .option(ChannelOption.SO_BACKLOG, options.get(Options.KEY_SERVER_BACKLOG).get()) .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE).childHandler(factory); server.bind().addListener(f -> { if (f.isSuccess()) { logger.info(Asterisque.logPrefix(true) + ": startup server: " + Debug.toString(address)); future.complete(new Server(node, address, options) { @Override public void close() { master.shutdownGracefully(); } }); } else { logger.error(Asterisque.logPrefix(true) + ": server bind failure: " + Debug.toString(address), f.cause()); future.completeExceptionally(f.cause()); master.shutdownGracefully(); } }); return future; }
From source file:org.asterisque.netty.Netty.java
License:Apache License
/** * {@inheritDoc}/* w ww . ja v a 2s .c o m*/ */ public void close() { logger.trace("close()"); if (closing.compareAndSet(false, true)) { NioEventLoopGroup w = worker.getAndSet(null); if (w != null) { w.shutdownGracefully(); } } }
From source file:org.beykery.wormhole.WormRegistry.java
License:Apache License
public WormRegistry(int port, int workerSize) { if (port <= 0 || workerSize <= 0) { throw new IllegalArgumentException("??"); }/* w w w. j a va 2 s. c o m*/ services = new HashMap<>(); workers = new NioEventLoopGroup(workerSize); final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioDatagramChannel.class); bootstrap.group(nioEventLoopGroup); bootstrap.handler(new ChannelInitializer<NioDatagramChannel>() { @Override protected void initChannel(NioDatagramChannel ch) throws Exception { ChannelPipeline cp = ch.pipeline(); cp.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { DatagramPacket dp = (DatagramPacket) msg; WormRegistry.this.onMessage(dp); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { WormRegistry.this.onException(cause); } }); } }); ChannelFuture sync = bootstrap.bind(port).syncUninterruptibly(); channel = (NioDatagramChannel) sync.channel(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { nioEventLoopGroup.shutdownGracefully(); } })); }
From source file:org.jboss.errai.bus.server.io.websockets.WebSocketServer.java
License:Apache License
public void start() { final ErraiServiceConfigurator esc = svc.getConfiguration(); useSecureWebSocket = ErraiConfigAttribs.SECURE_WEB_SOCKET_SERVER.getBoolean(esc); final int port = ErraiConfigAttribs.WEB_SOCKET_PORT.getInt(esc); final ServerBootstrap bootstrap = new ServerBootstrap(); final WebSocketServerHandler webSocketHandler = new WebSocketServerHandler(svc); try {// w w w . ja v a 2 s . com final NioEventLoopGroup bossGroup = new NioEventLoopGroup(); final NioEventLoopGroup workerGroup = new NioEventLoopGroup(); final ChannelFuture channelFuture = bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { if (useSecureWebSocket) { final SslHandler sslHandler = SslHandlerFactory.buildSslHandler(esc); ch.pipeline().addLast("ssl", sslHandler); } ch.pipeline().addLast("codec-http", new HttpServerCodec()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("handler", webSocketHandler); } }).bind(port).sync(); svc.addShutdownHook(new Runnable() { @Override public void run() { try { webSocketHandler.stop(); channelFuture.channel().close(); log.info("web socket server stopped."); } catch (Exception e) { throw new RuntimeException(e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }); } catch (Throwable t) { throw new RuntimeException(t); } log.info("started web socket server on port: " + port); }
From source file:org.onesec.raven.net.impl.NettyNioEventLoopGroupNode.java
License:Apache License
@Override protected void doStop() throws Exception { super.doStop(); NioEventLoopGroup _group = group.getAndSet(null); if (_group != null) _group.shutdownGracefully(); }
From source file:org.opendaylight.controller.netconf.test.tool.client.stress.StressClient.java
License:Open Source License
public static void main(final String[] args) { final Parameters params = parseArgs(args, Parameters.getParser()); params.validate();/* w w w .j a va 2 s . com*/ 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(); } }