netty的引用計數

來源:互聯網
上載者:User

標籤:

netty的引用計數文檔看http://netty.io/wiki/reference-counted-objects.html

為什麼會引用引用計數呢,Java中不是有gc線程幫我們回收對象嗎?我個人理解如下

1:netty為了實現zero copy使用了Direct Buffer,該buffer從Native Memory分配出來,分配和回收效率要遠低於在Java Heap上的對象,所以一般full gc來控制的,直接記憶體會自己檢測情況而調用system.gc(),通過使用引用計數可以自己來控制該buffer的釋放。具體看PlatformDependent.freeDirectBuffer(buffer)的實現。

這塊內容請看:http://blog.csdn.net/xieyuooo/article/details/7547435

2:netty使用了Pooled的功能。有點像c++的對象池,先分配一大塊記憶體,然後從裡面切出一塊一塊的供你使用,引用計數為0放入pool中,供後面使用。

如果不按按引用計數規則使用這兩種對象,將會導致記憶體泄露。所以測試的時候需要測試下是有有記憶體流失。

 

Netty引用計數的實現在AbstractReferenceCountedByteBuf代碼裡。

    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;

volatile是線程可見變數,儲存在Jvm的主記憶體中,而不是線程的工作記憶體裡面。然後使用jdk的原子庫對引用計數進行原子更新。
AtomicIntegerFieldUpdater,AtomicLongFieldUpdater,AtomicReferenceFieldUpdater通過反射原子更新對象的欄位,被更新的欄位是有要求的

1:必須是volatile類型,
2:注意訪問描述符(public ,protected ,defualt,private).
3: 只能是執行個體變數不能是類變數
4:對於AtomicIntegerFieldUpdater和AtomicLongFieldUpdater只能修改int/long類型的欄位,不能修改其封裝類型(Integer/Long)。如果要修改封裝類型就需要使用AtomicReferenceFieldUpdater

public class Updater {    public static void main(String[] args) throws InterruptedException {        Container c=new Container();          for(int i=0;i<1000;i++)          {              Task t=new Task(c);              t.start();              t.join(); //join方法在start後調用,調用線程會等待被調用的線程執行完成後執行          }        System.out.println("============="+c.index);    }}class Container{    public volatile  int index=0;}class Task extends Thread {    private AtomicIntegerFieldUpdater<Container> updater =            AtomicIntegerFieldUpdater.newUpdater(Container.class,"index");    private Container c;    public Task(Container c) {        this.c = c;    }    @Override    public void run() {        System.out.println(updater.getAndIncrement(c));        System.out.println(updater.getAndDecrement(c));    }}

 

netty的引用計數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.