Direct ByteBuffer Versus Heap Array

Heap buffers expose a backing array while direct buffers throw from array(), yet both share identical get/put APIs for the same byte-level reads.

JavaData Integrity

Code

snippet
import java.nio.ByteBuffer;

public class BufferAllocationFlavors {

    public static void main(String[] args) {
        ByteBuffer heap = ByteBuffer.allocate(16);
        ByteBuffer direct = ByteBuffer.allocateDirect(16);

        // 堆缓冲区背后就是 byte[];direct 缓冲区走堆外内存
        System.out.println("heap   isDirect=" + heap.isDirect() + " hasArray=" + heap.hasArray());
        System.out.println("direct isDirect=" + direct.isDirect() + " hasArray=" + direct.hasArray());

        // 堆缓冲区可以拿到底层数组做零拷贝读写
        byte[] backing = heap.array();
        System.out.println("heap.array().length = " + backing.length);

        // 直接缓冲区不承诺底层是数组:array() 抛 UnsupportedOperationException
        try {
            direct.array();
        } catch (UnsupportedOperationException e) {
            System.out.println("direct.array() throws UnsupportedOperationException");
        }

        // 两者对外 API 完全一致,读写代码不用改
        heap.putInt(0x1f2f3f4f);
        direct.putInt(0x1f2f3f4f);
        heap.flip();
        direct.flip();
        System.out.println("heap  getInt = 0x" + Integer.toHexString(heap.getInt()));
        System.out.println("direct getInt = 0x" + Integer.toHexString(direct.getInt()));
    }
}

Two allocations, one API surface

ByteBuffer.allocate(16) creates a heap buffer whose backing store is an ordinary byte[] — heap.hasArray() is true and heap.array() hands the array out for zero-copy access. ByteBuffer.allocateDirect(16) requests off-heap memory: direct.isDirect() is true, hasArray() is false, and the file proves the consequence by catching the UnsupportedOperationException that direct.array() throws — the comment’s point is that a direct buffer never promises an array behind it.

Parity in the printed values

heap   isDirect=false hasArray=true
direct isDirect=true hasArray=false
heap.array().length = 16
direct.array() throws UnsupportedOperationException
heap  getInt = 0x1f2f3f4f
direct getInt = 0x1f2f3f4f

The last two lines are the parity argument: both buffers take the same putInt(0x1f2f3f4f), flip(), getInt() sequence and return identical values, so read/write code does not branch on the allocation flavor.

The line that separates the flavors

System.out.println("direct isDirect=" + direct.isDirect() + " hasArray=" + direct.hasArray());

isDirect/hasArray are the two flags a generic byte-processing utility needs to check before attempting array() — everything else about the API is shared.

Interactive Tools for This Topic

FAQ

What does Direct ByteBuffer Versus Heap Array print when run?
Execute the whole file; each printed line is prefixed with a label like `heap isDirect=`, `direct isDirect=`, `heap.array().length =`.