Search code examples
nettydirect-buffer

How do I correctly work with ByteToMessageCodec.encode and direct buffers


I use a ByteToMessageCodec in my netty project. The encode has the following structure:

protected abstract void encode(
    ChannelHandlerContext ctx,
    I msg,
    ByteBuf out
) throws Exception

In my case the msg is a message that holds a directBuffer that came from another channel and is to be forwarded.

My Questions:

  • What is the best practice if out.isWritable() is false?
  • Does out.writeBytes(myMessage.directBuffer) copy the memory if out is also a direct buffer?
  • If it does copy the memory, can I just call ctx.writeAndFlush(myMessage.directBuffer) to prevent the memory copy?

There is a source by norman maurer telling something about this exact topic, but it seems to memory copy the buffers and doesn't answer all my questions.


Solution

  • You should not use a ByteToMessageCodec at all and just use MessageToMessageEncoder in this case:

    Then you could do:

    protected abstract void encode(ChannelHandlerContext ctx, I msg, List<Object> out) {
        out.add(msg.directBuffer);
    }
    

    This will prevent any memory copies.