2
votes

I am using ChannelInboundHandlerAdapter class and writeAndFlush every message that came from channelRead();

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
    ByteBuf msgBuffer = (ByteBuf)msg;
    BinaryWebSocketFrame frame= new BinaryWebSocketFrame(msgBuffer);
    ctx.writeAndFlush(frame);
}

In this case: Does Netty release "frame" and the "msg". I know that they are reference counted object, thus when I try to release them manually like the following:

public void channelRead(ChannelHandlerContext ctx, Object msg) throws  Exception { 
    ByteBuf buf = (ByteBuf)msg;
    BinaryWebSocketFrame frame= new BinaryWebSocketFrame(buf);
    ctx.writeAndFlush(frame);
    buf.release();
    frame.release();
}

But in that case I am getting refCounted object release error which is the following:

io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1

At first, I relied on netty that it releases the related instances but it gave me memory leak error on runtime occasionally.

How to reduce memory usage in such case because creating new instances in every channelRead event is not good idea when you can not release them properly.

1

1 Answers

4
votes

Yeah if you call writeAndFlush(...) you are basically transfer the ownership of the buffer. Netty itself will release the buffer if it was written or if the write fails.