Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does DirectByteBuffer.array() have extra size?

My code is:

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

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

My camera resolution is 1280×720, thus frameRGBABuffer should allocate 3686400 bytes of space.

But it is strange that the length of frameRGBABuffer.array() is 3686407. Why does it have extra 7 bytes spaces?

By the way, frameRGBABuffer.array() throws no exceptions and returns a byte[] with datas

It seems that Android allocate 7 extra spaces to handle the alignment. The source code is :

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;
}
like image 509
zccneil Avatar asked May 29 '18 06:05

zccneil


1 Answers

Here is the code behind it (JVM, not Android, but probably similar on 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() <--- is the key

// 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.

This is low level stuff for performance.

According to this researcher this is overkill on recent Intel cpus. Read more here: https://lemire.me/blog/2012/05/31/data-alignment-for-speed-myth-or-reality/

like image 74
Christophe Roussy Avatar answered Nov 09 '22 22:11

Christophe Roussy