channelInactive调用后的链式操作

时间:2019-07-13 04:15:31

标签: java netty

channelInactive中有一些清理代码:

public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    clean-up code
    super.channelInactive(ctx);
}

有时候,我需要主动断开频道:

ChannelFuture f = channel.disconnect();
f.addListener(new ChannelFutureListener() {
     public void operationComplete(ChannelFuture future) {
         // the problem is the channelInactive might not be called yet
         // how can I make sure channelInactive has been called?
         do something but the clean-up code in channelInactive MUST be called
     }
});

1 个答案:

答案 0 :(得分:0)

Netty无法执行此操作。如果channel.disconnect在netty的事件循环中未调用,它将以异步方式触发那些诸如channelInactive的事件,因此在disconnect之间没有顺序,并且其相关事件也会被触发。

AbstractChannelHandlerContext中的代码:

static void invokeChannelInactive(final AbstractChannelHandlerContext next) {
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeChannelInactive();
    } else {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                next.invokeChannelInactive();
            }
        });
    }
}