21

Is there any difference? Is ctx.close just a shorter version of ctx.channel.close?

2 Answers 2

35

Let's say we have three handlers in the pipeline, and they all intercept the close() operation, and calls ctx.close() in it.

ChannelPipeline p = ...;
p.addLast("A", new SomeHandler());
p.addLast("B", new SomeHandler());
p.addLast("C", new SomeHandler());
...

public class SomeHandler extends ChannelOutboundHandlerAdapter {
    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
        ctx.close(promise);
    }
}
  • Channel.close() will trigger C.close(), B.close(), A.close(), and then close the channel.
  • ChannelPipeline.context("C").close() will trigger B.close(), A.close(), and then close the channel.
  • ChannelPipeline.context("B").close() will trigger A.close(), and then close the channel.
  • ChannelPipeline.context("A").close() will close the channel. No handlers will be called.

So, when you should use Channel.close() and ChannelHandlerContext.close()? The rule of thumb is:

  • If you are writing a ChannelHandler and wanna close the channel in the handler, call ctx.close().
  • If you are closing the channel from outside the handler (e.g. you have a background thread which is not an I/O thread, and you want to close the connection from that thread.)
4
  • In general, ctx.channel.close should be used? Can you give examples where ctx.close should be used?
    – Ngoc Dao
    Jan 21, 2014 at 7:38
  • 2
    In general you can use ctx.close() when you know the "later" ChannelHandler's in the ChannelPipeline not care about the close event. Jan 21, 2014 at 17:42
  • ChannelInboundHandlerAdapter does not have a close() method, so we cannot @Override and the bullet points don't make sense to me. @trustin am I missing something? Thanks Jan 4, 2017 at 0:36
  • @Aaron Thanks for reporting. It should be ChannelOutboundHandlerAdapter.
    – trustin
    Jan 10, 2017 at 2:23
29

ctx.close() starts to flow through the ChannelPipeline from the point of the ChannelHandlerContext while ctx.channel().close() will start from the tail of the ChannelPipeline all the time.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.