使用zmq,probuf,缓冲池实现序列化和反序列化框架(一)-使用ConcurrentLinkedQueue实现缓冲池

ConcurrentLinkedQueue是并发包中可以保证一些情况下线程安全的队列。使用队列来实现缓冲池考虑到了缓冲池经常分配回收的特性,就像一个队列一样。

关于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());
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值