mina中没有直接使用java nio中原生的ByteBuffer作为底层缓存流处理方式,具体的原因官方给出的主要是:
1、NIO ByteBuffer没提供很可用的getters 和putters 。
2、很难在固定的大小中写入可变长度的数据。
当然mina并不是不让我们用原生的nio的ByteBuffer,这一点我们可以从IoBuffer的allocat方法得知:
public static IoBuffer allocate(int capacity, boolean direct)
public static IoBuffer allocate(int capacity)第一个参数是buffer的大小,第二次参数是true表示用nio的 ByteBuffer,false表示用mina中的buffer。
如果要创建一个自动扩充的buffer来说,nio的bytebuffer很不方便,因为这需要额外的工作来做,也就是我们需要自己实现一个小插件才行,当然用mina的buffer就方便多了:
IoBuffer buffer = IoBuffer.allocate(8);
buffer.setAutoExpand(true);
buffer.putString("12345678", encoder);
// Add more to this buffer
buffer.put((byte)10);
buffer除了可以自动扩充以外也可以自动收缩:
package com.test;
import org.apache.mina.core.buffer.IoBuffer;
public class TestOther {
public static void main(String[] args) {
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
因为我们定义了最小的长度是16,所以不满16的时候调用shrink方法不会去收缩的,当设置为大小为32的时候却只用了一半的空间来存储,调用shrink后剩下的不用的空间就会被释放,大小也会减半,这样有利于资源的充分利用。
IoBufferAllocater 接口是分配和管理buffer策略的,默认为SimpleBufferAllocator,也就是每次创建一个新的buffer,当然了CachedBufferAllocator会重用buffer,这样能获得更好的性能。