ConcurrentLinkedQueue是并发包中可以保证一些情况下线程安全的队列。使用队列来实现缓冲池考虑到了缓冲池经常分配回收的特性,就像一个队列一样。
简单的代码实现:
package com.zjq.stream;
import java.util.concurrent.ConcurrentLinkedQueue;
public class BufferPoolTest {
//定义缓冲池
private static final ConcurrentLinkedQueue<byte[]> bufferPool = new ConcurrentLinkedQueue<byte[]>();
private static final int bufferSize = 2 * 1024 * 1024;// 2MB
/**
* 申请分配缓冲
* @return
*/
public static byte[] allocateBuffer() {
byte[] result = bufferPool.poll();
System.out.println("使用:池中的缓存现在有" + bufferPool.size() + "个"+" HashCode:"+bufferPool.hashCode());
if (result == null) {
result = new byte[bufferSize];
System.out.println("申请了一个新的缓冲");
} else {
System.out.println("使用池中的缓存");
}
return result;
}
/*
* 回收缓冲
*/
public static void recycleBuffer(byte[] b) {
bufferPool.add(b);
System.out.println("回收:池中的缓存现在有" + bufferPool.size() + "个"+" HashCode:"+bufferPool.hashCode());
}
}