ByteBuffer 用于 NIO, 常见的还有其他几种基本类型的Buffer类, 创建的时候有None-direct 和 direct 方式之分, 后者直接在native I/O操作buffer, 避免在操作系统操作之后的额外拷贝动作,不占用JVM内存,适用于空间占用比较大,长生命周期的buffer。前者也可以通过JNI 来创建,一般是是在内存里面。通过链式调用,优点就是堆内分配垃圾回收比较快,缺点是需要内存复制,但是direct 方式就解决了这个问题,所以如果涉及到I/O通信比较多的,采用direct方式,后台业务的采用HeapByteBuffer。
下面是一些常用方法:
// 分配直接byte buffer
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity);
}
//分配一般byte buffer
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
//在当前position 读取一个byte,然后position 增加。
public abstract byte get();
//在当前的position 写入
public abstract ByteBuffer put(byte b);
//赋值给 dst 字节数组
public ByteBuffer get(byte[] dst) {
return get(dst, 0, dst.length);
}
下面主要分析Buffer 类:
(1) capacity : 包含的元素数量,且创建之后就不可变。
(2)limit : 标志不可读写的元素索引。
(3)postion: 读写元素的位置
(4) mark : reset 时设置的postion 备份。
mark <= position <= limit <= capacity
下面是一些常见的函数:
//给即将准备写的操作腾出空间(已经读,或者put的系列操作)
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
// 剩下的可操作数目
public final int remaining() {
return limit - position;
}
example :
import java.nio.ByteBuffer;
public class ByteBufferTest {
public static void main(String[] args) throws InterruptedException {
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
ByteBuffer buffer = ByteBuffer.allocateDirect(1024*100);
for(int i = 0; i < 1024*100; i ++){
buffer.put(new Byte("1"));
}
buffer.flip();
buffer.get();
buffer.limit(1024*100);
System.out.println(Runtime.getRuntime().freeMemory());
for(int i = 0; i < 1024*100; i ++){
System.out.println(buffer.get(i));
}
buffer.clear();
System.out.println(Runtime.getRuntime().freeMemory());
}
}
也正是因为ByteBuffer 有这么多的操作以及其局限性(postion,需要手工flip,rewind等等),在NIO 编程中,使用Netty 里面封装的ByteBuf,在Bytebuf 中,使用了readerIndex 和 writerIndex,而且是动态拓展大小的,采用的策略是先倍增再步进的方式进行逼近。
- BEFORE discardReadBytes()
+-------------------+------------------+------------------+
| discardable bytes | readable bytes | writable bytes |
+-------------------+------------------+------------------+
| | | |
0 <= readerIndex <= writerIndex <= capacity
- AFTER discardReadBytes()
+------------------+--------------------------------------+
| readable bytes | writable bytes (got more space) |
+------------------+--------------------------------------+
| | |
- readerIndex (0) <= writerIndex (decreased) <= capacity
其中discardable bytes 表示 可以被丢弃的字节,用于节省空间。
但是我们要知道,Netty 的byteBuffer 实际上面最终还是操作了ByteBuffer,所以就需要接口进行互换。