Does the following basic object pool work? I have a more sophisticated one based on the same idea (i.e. maintaining both a Semaphore and a BlockingQueue). My question is - do I need both Semaphore and BlockingQueue? Am I right that I don't need to do any synchronisation?
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();
}
}