Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

netty

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));
    }

}
like image 492
Chriss Avatar asked Dec 16 '13 13:12

Chriss


1 Answers

By default MessageToMessageEncoder releases original message after encoding. It's consistent with the typical use case of MessageToMessageEncoder, when your encoder returns new message as a result of encoding, so that original message can be safely discarded after encoding.

However, orginal message should not be discarded when it's used as a part of the result, as in your case. In this case you need to call retain() explicitly.

From the javadoc of MessageToMessageEncoder:

Be aware that you need to call ReferenceCounted.retain() on messages that are just passed through if they are of type ReferenceCounted. This is needed as the MessageToMessageEncoder will call ReferenceCounted.release() on encoded messages.

like image 132
axtavt Avatar answered Sep 23 '22 00:09

axtavt