When I have to call ByteBuf.retain() in a Netty4 Encoder?

Viewed 2631

I am writing a Encoder that NUL-Terminates a JSON-Message so it can be decoded in case the message is fragmented.

I found this sample ->click where ByteBuf.retain() was called in the end to write an existing ByteBuf to the output. Why did they do that, and why is it needed?

Here's my Encoder:

public class FrameEncoder extends MessageToMessageEncoder<ByteBuf> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        out.add(msg.retain());
        out.add(ctx.alloc().buffer(1).writeByte(NUL));
    }

}
1 Answers
Related