/**
* 一个可重复利用内存缓存区
* @author shanl
*
*/
public class MemBuffer {
// private final ByteBuffer buffer;
// private ByteBuffer tmpBuffer = null;
final private byte[] buffer;
private byte[] tmpBuffer = null;
private int size = 32 * 1024;
/**
* 创建一块默认大小的缓存区
*/
public MemBuffer(){
this(32 * 1024);
// buffer = ByteBuffer.allocateDirect(size);
}
/**
* 创建一块指定大小的缓存区
* @param size
*/
public MemBuffer(int size){
this.size = size;
buffer = new byte[size];
// buffer = ByteBuffer.allocateDirect(size);
}
/**
* 分配一块不少于size的缓存区
* @param size
* @return
*/
public byte[] alloc(int size){
if(this.size >= size){
tmpBuffer = buffer;
}else{
// tmpBuffer = ByteBuffer.allocateDirect(size);
tmpBuffer = new byte[size];
}
// tmpBuffer.position(0);
return tmpBuffer;
}
/**
* 分配一块byte缓存,并对部分数据赋值<br>
* 所分配的缓存区可能会比bys.length()大
* @param bys
* @param offset
* @param len
* @return
*/
public byte[] alloc(byte[] bys, int offset, int len){
// ByteBuffer buffer = alloc(bys.length);
// buffer.put(bys, offset, len);
byte[] buffer = alloc(bys.length);
System.arraycopy(bys, offset, buffer, 0, len);
return buffer;
}
/**
* 回收分配的缓存区
*/
public void free(){
// if(this.size < tmpBuffer.capacity()){
// tmpBuffer = null;
// }
if(null == tmpBuffer){
return;
}
if(this.size < tmpBuffer.length){
tmpBuffer = null;
}
}
}
MemBuffer
最新推荐文章于 2021-04-10 15:23:35 发布