日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

AbstractReferenceCountedByteBuf源码分析

發(fā)布時(shí)間:2024/2/28 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 AbstractReferenceCountedByteBuf源码分析 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)層面提供。

@Overridepublic final 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;}}}

每調(diào)用一次release方法,計(jì)數(shù)器減1
同樣用compareAndSet進(jìn)行自旋操作。

總結(jié)

以上是生活随笔為你收集整理的AbstractReferenceCountedByteBuf源码分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。