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包下的兩個(gè)重要的類(lèi)
1.AtomicInteger的使用
AtomicInteger ?=new AtimicInteger(0);
這樣變量i就有了原子性
2.AtomicintegerFieldUpdater的使用
public static AtomicIntegerFieldUpdaternewUpdater(Class tclass,
String fieldName)
這里就不詳細(xì)分析他的源碼了,其實(shí)很簡(jiǎn)單,他讓tclass的成員fieldName具有了原子性,是不是很簡(jiǎn)單~
研究完再回來(lái)看他的成員變量,實(shí)在不能太簡(jiǎn)單。
AbstractReferenceCountedByteBuf源碼實(shí)現(xiàn),該類(lèi)主要是實(shí)現(xiàn)引用計(jì)算的常規(guī)方法,充分利用voliate內(nèi)存可見(jiàn)性與CAS操作完成refCnt變量的維護(hù)。
2.實(shí)現(xiàn)的函數(shù)
在這個(gè)類(lèi)的函數(shù)中,看到了很熟悉的東西release(),retain(),refcnt(),touch()這些方法,天吶,這不就是ByteBuf類(lèi),AbstarctByteBuf類(lèi)中沒(méi)有實(shí)現(xiàn)的方法嗎?原來(lái)都拿到這里來(lái)實(shí)現(xiàn)了。上代碼!
@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;}每調(diào)用一次retain方法,計(jì)數(shù)器加一
compareAndSet方法用來(lái)獲取自己的值和期望的值進(jìn)行比較,如果其間被其他線程修改了,那么比對(duì)失敗,進(jìn)行自旋操作,重新獲得計(jì)數(shù)器重新比較
compareAndSet這個(gè)方法是CAS操作,由操作系統(tǒng)層面提供。
每調(diào)用一次release方法,計(jì)數(shù)器減1
同樣用compareAndSet進(jìn)行自旋操作。
總結(jié)
以上是生活随笔為你收集整理的AbstractReferenceCountedByteBuf源码分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: AbstractByteBuf源码分析
- 下一篇: UnpooledHeadByteBuf源