SimpleChannelInboundHandler和ChannelInboundHandlerAdapter的区别

转载自:https://www.jianshu.com/p/93ce43a0eb16

 

1. 源码分析

  1. SimpleChannelInboundHandler
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        boolean release = true;
        try {
            if (acceptInboundMessage(msg)) {
                @SuppressWarnings("unchecked")
                I imsg = (I) msg;
                channelRead0(ctx, imsg);
            } else {
                release = false;
                ctx.fireChannelRead(msg);
            }
        } finally {
            if (autoRelease && release) {
                ReferenceCountUtil.release(msg);
            }
        }
    }
  1. ChannelInboundHandlerAdapter
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.fireChannelRead(msg);
    }

从源码上上面,我们可以看出,当方法返回时,SimpleChannelInboundHandler会负责释放指向保存该消息的ByteBuf的内存引用。而ChannelInboundHandlerAdapter在其时间节点上不会释放消息,而是将消息传递给下一个ChannelHandler处理。

2. 从类定义看

  1. SimpleChannelInboundHandler
public abstract class SimpleChannelInboundHandler extends ChannelInboundHandlerAdapter {
  1. ChannelInboundHandlerAdapter
public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler

从类的定义中,我们可以看出

  • SimpleChannelInboundHandler是抽象类,而ChannelInboundHandlerAdapter是普通类,
  • SimpleChannelInboundHandler支持泛型的消息处理,而ChannelInboundHandlerAdapter不支持泛型



作者:雨中星辰0
链接:https://www.jianshu.com/p/93ce43a0eb16
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

你可能感兴趣的:(SimpleChannelInboundHandler和ChannelInboundHandlerAdapter的区别)