在这段代码中,shutdownGracefully()。syncUninterruptibly()永远不会返回。 这是预期的行为还是我误解了某些东西? 与网状4.0.35.FinalShutdownGracefully()永不返回
public class ShutdownGracefullyDemo {
private ServerBootstrap bootstrap;
public static void main(String[] args) throws Exception {
new ShutdownGracefullyDemo().initialize();
}
private void initialize() throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
bootstrap = new ServerBootstrap();
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new MyInboundHandler())
.bind(2025)
.sync()
.channel()
.closeFuture()
.sync();
}
@ChannelHandler.Sharable
private class MyInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {
Charset charset = Charset.forName("US-ASCII");
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
throws Exception {
String data = msg.toString(charset);
System.out.println("Received: " + data);
if ("quit\r\n".equals(data)) {
shutdown();
}
}
}
private void shutdown() {
if (bootstrap != null && bootstrap.group() != null) {
bootstrap.group().shutdownGracefully().syncUninterruptibly();
System.out.println("shutdown completed");
}
}
}
谢谢Derek的回答!在我的片段中,我从Norman Maurer的书“Netty in action”中得到了启发,在shutdown例子中,future.syncUninterruptibly()方法在'shutdownGracefully()'之后调用,实际上是调用shutdown的underneth逻辑,操作完成对我有意义。但由于某种原因,让我感到困惑的是,这并不像预期的那样有效,因为没有人通知等待线程。 – staedler
服务器可能正在等待所有客户端通道关闭,并且此任务在此通道上执行,如死锁,因此您可以创建一个关闭的新线程(或其他更好的方法)。 –