Reputation: 14780
As it is said in the doc:
When an outbound (a.k.a. downstream) message reaches at the beginning of the pipeline, Netty will release it after writing it out.
So in normal case, the reference count of ByteBuf
will be decreased after writeAndFlush is called successfully.
What about error occurs?
Suppose I have two channels : firstChannel
& secondChannel
. If the ByteBuf
is failed to sent to the firstChannel
then it need be sent to the secondChannel
Code example is below.
final ChannelFuture future = firstChannel.writeAndFlush(byteBuf.asReadOnly()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
// Is the reference count decreased already before entering this method?
if (!future.isSuccess()) {
byteBuf.retain();
secondChannel.writeAndFlush(byteBuf);
}
}
});
Will the reference count be decreased even if error occurs?
Is the reference count decreased already before operationComplete
is fired?
Upvotes: 1
Views: 1605
Reputation: 23557
Even on failure it will release the buffer so your code will not work. You would need to retain()
the buffer to ensure the increment count is 1 when the listener is called and then decrement it by your self if the future was successful.
Something like this:
final ChannelFuture future = firstChannel.writeAndFlush(byteBuf.retain().duplicate()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
secondChannel.writeAndFlush(byteBuf);
} else {
byteBuf.release();
}
}
});
Also note that I call duplicate()
as well to ensure we not modify the reader/writer index of the buffer that may be passed to the second channel later on.
Upvotes: 3