ByteBuffer的三种实现为:
- HeapByteBuffer 堆内存
- DirectByteBuffer 堆外/直接内存
- MappedByteBuffer 堆外/文件映射
一、ByteBuffer
ByteBuffer是java nio中的一种数据结构。主要用来保存从Socket中读写字节流,可以循环使用,有效降低GC压力。
内部有一个固定长度的byte[]。用三个数字来控制读写:capacity数组 总长度、position当前读写位置,当前读写上限。
flip()操作:将position赋值给limit, positon设置为0。
二、HeapByteBuffer
本质上是具有ByteBuffer视图的byte数组。
创建方法1:
- ByteBuffer的静态方法
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
创建方法2:
public static ByteBuffer wrap(byte[] array,
int offset, int length)
{
try {
return new HeapByteBuffer(array, offset, length);
}