apache mina 学习(九)-----IoBuffer

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,这样能获得更好的性能。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值