ByteBuffer用法
2020-01-13 本文已影响0人
DD_Dog
ByteBufer简介
ByteBufer是用来处理子节的,比传统的数组的效率要高。
HeapByteBuffer用子节数组封装的一种的ByteBuffer,分配在堆上,受GC控制。
DircectByteBuffer不是分配在堆上,不受GC控制。
两者的区别
- 创建和释放DirectByteBuffer的代价要比HeapByteBuffer要高
- DirectByteBuffer的读写的操作要比HeapByteBuffer要快
基本使用
1. HeadByteBuffer
ByteBuffer heapByteBuffer = ByteBuffer.allocate(20);
源码如下:
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
HeapByteBuffer(int cap, int lim, boolean isReadOnly) {
// package-private
super(-1, 0, lim, cap, new byte[cap], 0);
this.isReadOnly = isReadOnly;
}
ByteBuffer(int mark, int pos, int lim, int cap, byte[] hb, int offset) {
super(mark, pos, lim, cap, 0);
this.hb = hb;
this.offset = offset;
}
新生成了一个长度为capacity的数组,以及一些标示
##2.获取DirectByteBuffer对象
ByteBuffer directByteBuffer = ByteBuffer.allocateDirect(20);
源码如下:
public static ByteBuffer allocateDirect(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity < 0: " + capacity);
}
DirectByteBuffer.MemoryRef memoryRef = new DirectByteBuffer.MemoryRef(capacity);
return new DirectByteBuffer(capacity, memoryRef);
}
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;
}
由runtime去申请了了一块内存,不是直接在堆内存中。
再说基本操作之前,先简单说下的ByteBuffer常见的四个标示
1. position:当前读或者写的位置
2. mark:标记上一次mark的位置,方便reset将postion置为mark的值。
3. limit:标记数据的最大有效的位置
4. capacity:标记buffer的最大可存储值
其中在任意的时候。都必须满足
mark<=position<=limit<=capacity
#参考
[ByteBuffer基本用法](https://blog.csdn.net/zhi184816/article/details/52462148)