以下基本对象池是否正常工作?我有一个更加复杂的基于同样的想法(即维护一个信号量和一个BlockingQueue).我的问题是 – 我需要同时使用信号量和BlockingQueue吗?我是对的,我不需要做任何同步吗?
import java.util.Collection; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Semaphore; public final class Pool<T> { private final BlockingQueue<T> objects; private final Semaphore permits; public Pool(Collection<? extends T> objects) { // we have as many permits as objects in our pool: this.permits = new Semaphore(objects.size()); this.objects = new ArrayBlockingQueue<T>(objects.size(),false,objects); } public T borrow() { this.permits.acquireUninterruptibly(); // we have a permit,so there must be one in there: return this.objects.poll(); } public void giveBack(T object) { this.objects.add(object); this.permits.release(); } }
解决方法
如已经指出的那样,一个有限的BlockingQueue就足够了.例如,以下代码将执行您想要的:
import java.util.Collection; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public final class Pool<T> { private final BlockingQueue<T> objects; public Pool(Collection<? extends T> objects) { this.objects = new ArrayBlockingQueue<T>(objects.size(),objects); } public T borrow() throws InterruptedException { return this.objects.take(); } public void giveBack(T object) throws InterruptedException { this.objects.put(object); } }
另外,您可能需要考虑使用BlockingQueue.poll()来支持借用()的定时版本.
如果您没有有限的阻塞队列数据结构,那么您可以在任何数据结构之上强加一个信号量,以创建线程安全和绑定的行为.