Netty中常见的IllegalReferenceCountException异常原因及解决

  • 原因
  • 解决方法
错误异常
  • 我们在使用Netty过程中是不是经常遇到如下异常:
io.netty.util.IllegalReferenceCountException: refCnt: 0, increment: 1
	at io.netty.buffer.AbstractReferenceCountedByteBuf.release0(
	AbstractReferenceCountedByteBuf.java:100)
	...
原因
  • SimpleChannelInboundHandler 它会自动进行一次释放(即引用计数减1). 源码如下:
  @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);
            }
        }
    }
解决办法
  • ((FullHttpRequest) msg).retain();
  • 调用 msg.retain() 方法进行手动计数器加1

猜你喜欢

转载自blog.csdn.net/xxyybs/article/details/102860538