Does this basic Java object pool work?

Are the following basic object pools working properly? I have a more complex one based on the same idea (i.e. maintaining a semaphore and a BlockingQueue) My question is – do I need to use semaphores and BlockingQueue at the same time? I'm right. Don't I need to do any synchronization?

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

Solution

As already pointed out, a limited BlockingQueue is sufficient For example, the following code will do what you want:

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

In addition, you may need to consider using BlockingQueue Poll() to support borrowing the scheduled version of ()

If you do not have limited blocking queue data structures, you can impose a semaphore on any data structure to create thread safe and binding behavior

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>