class MemoryPool<T> { private Queue<T> pool; public MemoryPool() { pool = new LinkedList<>(); } public synchronized T allocate() { if (pool.isEmpty()) { return createObject(); } return pool.poll(); } public synchronized void deallocate(T object) { pool.offer(object); } private T createObject() { return new T(); } } class LowGCMemoryQueue<T> { private MemoryPool<T> memoryPool; private Queue<T> queue; public LowGCMemoryQueue() { memoryPool = new MemoryPool<>(); queue = new LinkedList<>(); } public synchronized void enqueue(T object) { queue.offer(object); } public synchronized T dequeue() { T object = queue.poll(); memoryPool.deallocate(object); return object; } } public class Main { public static void main(String[] args) { LowGCMemoryQueue<String> queue = new LowGCMemoryQueue<>(); queue.enqueue("Object 1"); queue.enqueue("Object 2"); String object1 = queue.dequeue(); System.out.println(object1); String object2 = queue.dequeue(); System.out.println(object2); } }


上一篇:
下一篇:
切换中文