Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Netty 4, what's the difference between ctx.close and ctx.channel.close?

Tags:

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

like image 832
Ngoc Dao Avatar asked Jan 20 '14 17:01

Ngoc Dao


1 Answers

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.)
like image 151
trustin Avatar answered Oct 11 '22 11:10

trustin