eric zhao
eric zhao

Reputation: 175

Create a Netty ByteBuf

If I just want to use ByteBuf not in a Netty application.I use ByteBuf buf = Unpooled.wrappedBuffer(bytes) to create a ByteBuf,must I call the buf.release in the end of the function?

 public void process(byte[] bytes) {

            ByteBuf frame = Unpooled.wrappedBuffer(bytes);

//something
            frame.release();
        }

Upvotes: 1

Views: 1082

Answers (2)

Norman Maurer
Norman Maurer

Reputation: 23557

As rule of thumb you should always call ByteBuf.release() once your are done with using the ByteBuf. This will allow you to switch to direct buffers or pooled buffers later without any code changes.

Upvotes: 1

Derek J.
Derek J.

Reputation: 126

The UnpooledHeapByteBuf.release method implement like this:

@Override
public boolean release() {
    for (;;) {
        int refCnt = this.refCnt;
        if (refCnt == 0) {
            throw new IllegalReferenceCountException(0, -1);
        }

        if (refCntUpdater.compareAndSet(this, refCnt, refCnt - 1)) {
            if (refCnt == 1) {
                deallocate();
                return true;
            }
            return false;
        }
    }
}

And the deallocate method:

@Override
protected void deallocate() {
    array = null;
}

The heap memory can be recycle by garbage collector, so not call the release method maybe not make memory leak in theory in my opinion.

Upvotes: 1

Related Questions