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

xiaoxiao2021-02-28  80

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

转载请注明原文地址: https://www.6miu.com/read-44416.html

最新回复(0)