Mina学习之IoBuffer

IoBuffer是一个被MINA体系所使用的字节数组。它是ByteBuffer的替代品,Mina不使用NIO的ByteBuffer有两个原因:

1. ByteBuffer没有提供更多有用的api,如fill,get/putString等

2. ByteBuffer是定长的,故无法写入变长的数据

IoBuffer的操作

分配新的Buffer

IoBuffer是一个抽象类,不能直接实例化,想分配IoBuffer,我们需要用以下两种方法中的一个:

// Allocates a new buffer with a specific size, defining its type (direct or heap)
public static IoBuffer allocate(int capacity, boolean direct)

// Allocates a new buffer with a specific size
public static IoBuffer allocate(int capacity)

其中,参数capacity表示该IoBuffer的容量,参数direct标识buffer的类型,true表示直接缓冲区,false表示堆缓冲区。

创建可自动扩展长度的Buffer

NIO API中想创建可扩展长度的缓冲区很不容易,因为buffer长度是固定的。IoBuffer引入了一个自动扩展的属性,该属性能够实现自动扩展缓冲区的长度。
当长度不够时,会自动将缓冲区的大小增加到2倍。
IoBuffer buffer = IoBuffer.allocate(8);
buffer.setAutoExpand(true);
buffer.putString("12345678", encoder);
// Add more to this buffer
buffer.put((byte)10);

创建可自动缩小长度的Buffer

同样,IoBuffer也提供了一个方法来释放多余的空间,如果autoShrink被打开后,调用compact()后只有1/4或者更少的空间被占用,IoBuffer则会缩小至一半的容量。

IoBuffer buffer = IoBuffer.allocate(16);
buffer.setAutoShrink(true);
buffer.put((byte)1);
System.out.println("Initial Buffer capacity = "+buffer.capacity());
buffer.shrink();
System.out.println("Initial Buffer capacity after shrink = "+buffer.capacity());
buffer.capacity(32);
System.out.println("Buffer capacity after incrementing capacity to 32 = "+buffer.capacity());
buffer.shrink();
System.out.println("Buffer capacity after shrink= "+buffer.capacity());
结果如下:
Initial Buffer capacity = 16
Initial Buffer capacity after shrink = 16
Buffer capacity after incrementing capacity to 32 = 32
Buffer capacity after shrink= 16




原文地址:https://www.cnblogs.com/marcotan/p/4256970.html