java – 为什么DirectByteBuffer.array()有额外的大小?

我的代码是:

if (frameRGBABuffer == null) {
    frameRGBABuffer = ByteBuffer.allocateDirect(cameraHeight * cameraWidth * 4)
        .order(ByteOrder.nativeOrder());
}

Log.d("tag",frameRGBABuffer.array().length)

我的相机分辨率是1280×720,因此frameRGBABuffer应该分配3686400字节的空间.

但是很奇怪frameRGBABuffer.array()的长度是3686407.为什么它有额外的7个字节空格?

顺便说一下,frameRGBABuffer.array()不会抛出异常并返回带有数据的byte []

似乎Android分配了7个额外的空间来处理对齐.
源代码是:

MemoryRef(int capacity) {
    VMRuntime runtime = VMRuntime.getRuntime();
    buffer = (byte[]) runtime.newNonMovableArray(byte.class, capacity + 7);
    allocatedAddress = runtime.addressOf(buffer);

    // Offset is set to handle the alignment: http://b/16449607
    offset = (int) (((allocatedAddress + 7) & ~(long) 7) - allocatedAddress);
    isAccessible = true;
    isFreed = false;
}

解决方法:

这是它背后的代码(JVM,不是Android,但在Android上可能类似):

 DirectByteBuffer(int cap) {                   // package-private

    super(-1, 0, cap, cap);
    boolean pa = VM.isDirectMemoryPageAligned();
    int ps = Bits.pageSize();
    long size = Math.max(1L, (long)cap + (pa ? ps : 0)); <----- HERE
    Bits.reserveMemory(size, cap);

    long base = 0;
    try {
        base = unsafe.allocateMemory(size);
    } catch (OutOfMemoryError x) {
        Bits.unreserveMemory(size, cap);
        throw x;
    }
    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;

VM.isDirectMemoryPageAligned()< ---是关键

// User-controllable flag that determines if direct buffers should be page
// aligned. The "-XX:+PageAlignDirectMemory" option can be used to force
// buffers, allocated by ByteBuffer.allocateDirect, to be page aligned.

这是性能低级的东西.

根据这位研究人员的说法,这对最近的英特尔公司来说太过分了.
在这里阅读更多:https://lemire.me/blog/2012/05/31/data-alignment-for-speed-myth-or-reality/

上一篇:3. Netty源码阅读之Channel


下一篇:java NIO 深入学习