在這段代碼中,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
服務器可能正在等待所有客戶端通道關閉,並且此任務在此通道上執行,如死鎖,因此您可以創建一個關閉的新線程(或其他更好的方法)。 –