前面几篇博客我们已经详细讲了ByteBuf对内存的分配,是时候来看一下他是如何释放内存的了:
buf.release();
我们进入这个方法看一下:
private boolean release0(int decrement) {
for (;;) {
int refCnt = this.refCnt;
if (refCnt < decrement) {
throw new IllegalReferenceCountException(refCnt, -decrement);
}
if (refCntUpdater.compareAndSet(this, refCnt, refCnt - decrement)) {
if (refCnt == decrement) {
deallocate();
return true;
}
return false;
}
}
}
如果当前的ByteBuf最终没有引用了,就会调用deallocate:
protected final void deallocate() {
if (handle >= 0) {
final long handle = this.handle;
//接下来这两行代码表示当前bytebuf已经不指向任何内存
this.handle = -1;
memory = null;
//之后就会调用free方法进行释放
chunk.arena.free(chunk, handle, maxLength, ca