Netty-DirectByteBuffery源码分析

Posted 征服.刘华强

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    

 

以上是关于Netty-DirectByteBuffery源码分析的主要内容,如果未能解决你的问题,请参考以下文章

免费分享20套微信小程序源码 源码免费下载强烈推荐

JDK源码集合源码目录,冲冲冲

android狼人杀源码,桌面源码,猎豹快切源码

Rxjava 源码解析 - 线程切换源码

Rxjava 源码解析 - 线程切换源码

Gradle获取源码sourceSets