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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

AbstractReferenceCountedByteBuf源码分析

發布時間:2024/2/28 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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操作,由操作系統層面提供。

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

每調用一次release方法,計數器減1
同樣用compareAndSet進行自旋操作。

總結

以上是生活随笔為你收集整理的AbstractReferenceCountedByteBuf源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。