Reusing of bytebuf in netty

后端 未结 1 968
南旧
南旧 2021-01-21 17:51

I have a http service with Netty. For a set of requests there is the same reply with just \"{}\" in http body. I had an idea to avoid creation of new buffer for each such reques

1条回答
  •  情歌与酒
    2021-01-21 18:10

    When sharing a Netty buffer, you need to follow the rules of basic reference counting, unlike the simple rules of basic garbage collection.

    These rules basically boil down to:

    • When sending a ByteBuf away from your class, call retain()
    • If you are done using a ByteBuf, call release()

    Most of the times, when you are done using a bytebuf at the same time as sending it away, you can remove both calls.

    Inside you example, when writing your shared ByteBuf to the socket, you should call retain() to increment the reference count, since the object is now used in 2 different places.

    There is still 1 trick you need to do after calling .retain(), that is calling .duplicate(), as this prevents modifications of the reader index from passing to to your base copy, failing to do so gives the problem of the first write succeeded, but after that all subsequent writes will write an empty buffer.

    0 讨论(0)
提交回复
热议问题