netty源码分析(27)- UnpooledByteBufAllocator分析

上一节查看了ByteBufAllocator,并了解了其抽象实现,和一些根据不同的内存类型进行内存分配的思路。

本节研究UnpooledByteBufAllocator,包括heapdirect的内存分配,以及Unsafe非unsafe的区别。

关于heap内存的分配
  • 入口
    @Override
    protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
        //判断是有unsafe来分配
        return PlatformDependent.hasUnsafe() ?
                new InstrumentedUnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
                new InstrumentedUnpooledHeapByteBuf(this, initialCapacity, maxCapacity);
    }
  • 查看new InstrumentedUnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
    发现分配UnpooledUnsafeHeap内存,其实是分配了一个byte数组,并保存在UnpooledHeapByteBuf#array成员变量中。该内存的初始值容量和最大可扩展容量可以指定。
    InstrumentedUnpooledUnsafeHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
            super(alloc, initialCapacity, maxCapacity);
    }

    UnpooledUnsafeHeapByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }

    public UnpooledHeapByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);

        checkNotNull(alloc, "alloc");

        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //设置array
        setArray(allocateArray(initialCapacity));
        //设置readerIndex和writerIndex指针初始值为0
        setIndex(0, 0);
    }

    protected byte[] allocateArray(int initialCapacity) {
        //初始化了一个新的byte数组
        return new byte[initialCapacity];
    }

    private void setArray(byte[] initialArray) {
        //保存数组
        array = initialArray;
        tmpNioBuf = null;
    }

    @Override
    public ByteBuf setIndex(int readerIndex, int writerIndex) {
        if (checkBounds) {
            checkIndexBounds(readerIndex, writerIndex, capacity());
        }
        //设置
        setIndex0(readerIndex, writerIndex);
        return this;
    }

    final void setIndex0(int readerIndex, int writerIndex) {
        //设置读写指针
        this.readerIndex = readerIndex;
        this.writerIndex = writerIndex;
    }

  • 查看new InstrumentedUnpooledHeapByteBuf(this, initialCapacity, maxCapacity);内存分配,其实例化过成和InstrumentedUnpooledUnsafeHeapByteBuf一样。在这里看不出safeunsafe的区别,经过之前的代码,可以重获取的时候 getByte方法进入查看.
    InstrumentedUnpooledHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
            super(alloc, initialCapacity, maxCapacity);
    }


    public UnpooledHeapByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);

        checkNotNull(alloc, "alloc");

        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //设置array
        setArray(allocateArray(initialCapacity));
        //设置readerIndex和writerIndex指针初始值为0
        setIndex(0, 0);
    }

  • 查看UnpooledHeapByteBuf#getByte()方法,堆内存类型的ByteBuf获取的时候。直接通过下标获取byte数组中的byte
    @Override
    public byte getByte(int index) {
        ensureAccessible();
        return _getByte(index);
    }

   @Override
    protected byte _getByte(int index) {
        //该array为初始化的时候,实例化的byte[]
        return HeapByteBufUtil.getByte(array, index);
    }

    static byte getByte(byte[] memory, int index) {
        //直接拿到一个数组
        return memory[index];
    }
  • 查看UnpooledUnsafeHeapByteBuf#getByte()方法,获取byte字节的时候,调用的是jdk的UNSAFE对象。
    @Override
    public byte getByte(int index) {
        checkIndex(index);
        return _getByte(index);
    }

    @Override
    protected byte _getByte(int index) {
        return UnsafeByteBufUtil.getByte(array, index);
    }

    static byte getByte(byte[] array, int index) {
        return PlatformDependent.getByte(array, index);
    }

    public static byte getByte(byte[] data, int index) {
        return PlatformDependent0.getByte(data, index);
    }

    static byte getByte(byte[] data, int index) {
        //通过UNSAFE去获取
        return UNSAFE.getByte(data, BYTE_ARRAY_BASE_OFFSET + index);
    }

关于direct内存的分配
  • 入口UnpooledByteBufAllocator#newDirectBuffer()
    @Override
    protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
        final ByteBuf buf;
        //判断是否有unsafe对象
        if (PlatformDependent.hasUnsafe()) {
            buf = noCleaner ? new InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf(this, initialCapacity, maxCapacity) :
                    new InstrumentedUnpooledUnsafeDirectByteBuf(this, initialCapacity, maxCapacity);
        } else {
            buf = new InstrumentedUnpooledDirectByteBuf(this, initialCapacity, maxCapacity);
        }
        return disableLeakDetector ? buf : toLeakAwareBuffer(buf);
    }
  • 跟踪buf = new InstrumentedUnpooledDirectByteBuf(this, initialCapacity, maxCapacity);可以发现,UnpooledDirect类型得内存分配实际上是维护了一个底层jdk的一个DirectByteBuffer。分配内存的时候就创建它,并将他保存到buffer成员变量。
    InstrumentedUnpooledDirectByteBuf(
            UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(alloc, initialCapacity, maxCapacity);
    }  

    public UnpooledDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);
        if (alloc == null) {
            throw new NullPointerException("alloc");
        }
        //检查合法性
        checkPositiveOrZero(initialCapacity, "initialCapacity");
        checkPositiveOrZero(maxCapacity, "maxCapacity");
        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //获取jdkDirectBuffer并保存到成员变量
        setByteBuffer(allocateDirect(initialCapacity));
    }

    private void setByteBuffer(ByteBuffer buffer) {
        ByteBuffer oldBuffer = this.buffer;
        //释放旧的buffer
        if (oldBuffer != null) {
            if (doNotFree) {
                doNotFree = false;
            } else {
                freeDirect(oldBuffer);
            }
        }
        //保存新buffer
        this.buffer = buffer;
        tmpNioBuf = null;
        capacity = buffer.remaining();
    }


    protected ByteBuffer allocateDirect(int initialCapacity) {
        //分配
        return ByteBuffer.allocateDirect(initialCapacity);
    }

    public static ByteBuffer allocateDirect(int capacity) {
        return new DirectByteBuffer(capacity);
    }

跟踪iUnpooledHeapByteBuf#_getByte(),就比较简单了,直接使用jdk的api获取。

    @Override
    protected byte _getByte(int index) {
        //使用buffer
        return buffer.get(index);
    }
  • 跟踪new InstrumentedUnpooledUnsafeDirectByteBuf(this, initialCapacity, maxCapacity);可以发现UnpooledUnsafeDirect的内存分配,和非Unsafe的区别在于它计算了一个内存首地址并且保存起来,在计算内存首地址的时候是通过UNSAFE对象去获取的。保存内存首地址的好处是可以在获取的时候直接通过计算下标直接获取。
        InstrumentedUnpooledUnsafeDirectByteBuf(
                UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
            super(alloc, initialCapacity, maxCapacity);
        }

    public UnpooledUnsafeDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
        super(maxCapacity);
        if (alloc == null) {
            throw new NullPointerException("alloc");
        }
        checkPositiveOrZero(initialCapacity, "initialCapacity");
        checkPositiveOrZero(maxCapacity, "maxCapacity");
        if (initialCapacity > maxCapacity) {
            throw new IllegalArgumentException(String.format(
                    "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity));
        }

        this.alloc = alloc;
        //分配jdk底层DirectByteBuffer,设置buffer
        setByteBuffer(allocateDirect(initialCapacity), false);
    }

    final void setByteBuffer(ByteBuffer buffer, boolean tryFree) {
        if (tryFree) {
            ByteBuffer oldBuffer = this.buffer;
            if (oldBuffer != null) {
                if (doNotFree) {
                    doNotFree = false;
                } else {
                    freeDirect(oldBuffer);
                }
            }
        }
        this.buffer = buffer;
        //计算内存地址
        memoryAddress = PlatformDependent.directBufferAddress(buffer);
        tmpNioBuf = null;
        capacity = buffer.remaining();
    }

    public static long directBufferAddress(ByteBuffer buffer) {
        return PlatformDependent0.directBufferAddress(buffer);
    }

    static long directBufferAddress(ByteBuffer buffer) {
        return getLong(buffer, ADDRESS_FIELD_OFFSET);
    }

    private static long getLong(Object object, long fieldOffset) {
        //调用UNSAFE获取内存地址
        return UNSAFE.getLong(object, fieldOffset);
    }

跟踪UnpooledUnsafeDirectByteBuf#_getByte(),可以知道UNSAFE的直接内存内容获取方式是通过内存首地址 + 偏移量获取的。

    @Override
    protected byte _getByte(int index) {
        //通过计算地址获取
        return UnsafeByteBufUtil.getByte(addr(index));
    }

    long addr(int index) {
        //直接从 内存首地址 + 偏移量 获取
        return memoryAddress + index;
    }

    static byte getByte(long address) {
        //address正是memoryAddress + index
        return UNSAFE.getByte(address);
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容