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
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:
ByteBuf
away from your class, call retain()
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.