实现说明
Direct 与 Heap 两种 ByteBuffer的核心是类 BufferAllocationFlavors和函数 main。
使用要点
- 直接运行文件,输出会带上标签,比如
heap isDirect=、direct isDirect=、heap.array().length =——输出的每一行都能指回产生它的那次调用。
常见问题
运行「Direct 与 Heap 两种 ByteBuffer」会打印什么?
整个文件跑完,输出行以 heap isDirect=、direct isDirect=、heap.array().length = 这类前缀开头。
核心语句
ByteBuffer direct = ByteBuffer.allocateDirect(16);
ByteBuffer heap = ByteBuffer.allocate(16);
byte[] backing = heap.array();
代码示例
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()));
}
}