Netty-DirectByteBuffery源碼分析

JVM參數  -XX:MaxDirectMemorySize=1024M  來設置可以使用的堆外內存大小。

代碼中可以使用VM工具類獲取

VM.maxDirectMemory()
DirectByteBuffer源碼分析
DirectByteBuffer(int cap) {                   // package-private

        super(-1, 0, cap, cap);
        //是否按頁對齊
        boolean pa = VM.isDirectMemoryPageAligned();
        //內存頁大小默認4096
        int ps = Bits.pageSize();
        long size = Math.max(1L, (long)cap + (pa ? ps : 0));
        //增加內部計數器-超量報oom異常
        Bits.reserveMemory(size, cap);

        long base = 0;
        try {
            //分配內存空間
            base = unsafe.allocateMemory(size);
        } catch (OutOfMemoryError x) {
        //減少計數器的值
            Bits.unreserveMemory(size, cap);
            throw x;
        }
        //把內存快都設置爲0
        unsafe.setMemory(base, size, (byte) 0);
        if (pa && (base % ps != 0)) {
            // Round up to page boundary
            address = base + ps - (base & (ps - 1));
        } else {
            //內存指針
            address = base;
        }
        //釋放器
        cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
        att = null;
    }

 

private static class Deallocator
        implements Runnable
    {

        private static Unsafe unsafe = Unsafe.getUnsafe();

        private long address;
        private long size;
        private int capacity;

        private Deallocator(long address, long size, int capacity) {
            assert (address != 0);
            //內存地址
            this.address = address;
            //大小
            this.size = size;
            this.capacity = capacity;
        }

        public void run() {
            //釋放內存
            unsafe.freeMemory(address);
            address = 0;
            //更新計數器
            Bits.unreserveMemory(size, capacity);
        }

    }

Put值通過address+index還計算出內存位置,調用unsafe直接賦值。

   public ByteBuffer put(byte x) {
        //unsafe.putBytes(address + (position++),  x);
        unsafe.putByte(ix(nextPutIndex()), ((x)));
        return this;
    }

 

發佈了175 篇原創文章 · 獲贊 70 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章