AbstractReferenceCountedByteBuf源码分析
1.成員變量
private static final AtomicIntegerFieldUpdater<AbstractReferenceCountedByteBuf> refCntUpdater;static {AtomicIntegerFieldUpdater<AbstractReferenceCountedByteBuf> updater =PlatformDependent.newAtomicIntegerFieldUpdater(AbstractReferenceCountedByteBuf.class, "refCnt");if (updater == null) {updater = AtomicIntegerFieldUpdater.newUpdater(AbstractReferenceCountedByteBuf.class, "refCnt");}refCntUpdater = updater;}private volatile int refCnt = 1;AtomicIntegerFieldUpdater是什么鬼?先研究一下atomic包下的兩個重要的類
1.AtomicInteger的使用
AtomicInteger ?=new AtimicInteger(0);
這樣變量i就有了原子性
2.AtomicintegerFieldUpdater的使用
public static AtomicIntegerFieldUpdaternewUpdater(Class tclass,
String fieldName)
這里就不詳細分析他的源碼了,其實很簡單,他讓tclass的成員fieldName具有了原子性,是不是很簡單~
研究完再回來看他的成員變量,實在不能太簡單。
AbstractReferenceCountedByteBuf源碼實現,該類主要是實現引用計算的常規方法,充分利用voliate內存可見性與CAS操作完成refCnt變量的維護。
2.實現的函數
在這個類的函數中,看到了很熟悉的東西release(),retain(),refcnt(),touch()這些方法,天吶,這不就是ByteBuf類,AbstarctByteBuf類中沒有實現的方法嗎?原來都拿到這里來實現了。上代碼!
@Overridepublic ByteBuf retain() {for (;;) {int refCnt = this.refCnt;if (refCnt == 0) {throw new IllegalReferenceCountException(0, 1);}if (refCnt == Integer.MAX_VALUE) {throw new IllegalReferenceCountException(Integer.MAX_VALUE, 1);}if (refCntUpdater.compareAndSet(this, refCnt, refCnt + 1)) {break;}}return this;}每調用一次retain方法,計數器加一
compareAndSet方法用來獲取自己的值和期望的值進行比較,如果其間被其他線程修改了,那么比對失敗,進行自旋操作,重新獲得計數器重新比較
compareAndSet這個方法是CAS操作,由操作系統層面提供。
每調用一次release方法,計數器減1
同樣用compareAndSet進行自旋操作。
總結
以上是生活随笔為你收集整理的AbstractReferenceCountedByteBuf源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AbstractByteBuf源码分析
- 下一篇: UnpooledHeadByteBuf源