繁体   English   中英

在java中是否有任何(无界)公平阻塞队列?

[英]Is there any (unbounded) fair blocking queue in java?

是否有任何阻塞队列的实现,如果多个使用者从同一队列中删除元素,则保证公平的take()操作。 我检查了LinkedBlockingQueue,LinkedTransferQueue,看起来两者都不公平。 ArrayBlockingQueue提供了公平的操作,但它有限。

我们可以使用像ConcurrentLinked队列和公平的信号量这样的无界队列来实现无限公平阻塞队列。 下面的类没有实现BlockingQueue接口中的所有方法,只是其中一些用于演示目的。 main()方法仅作为测试编写。

public class FairBlockingQueue<T> {

    private final Queue<T> queue;
    private final Semaphore takeSemaphore;

    public FairBlockingQueue() {
        queue = new ConcurrentLinkedQueue<T>();
        takeSemaphore = new Semaphore(0, true);
    }

    public FairBlockingQueue(Collection<T> c) {
        queue = new ConcurrentLinkedQueue<T>(c);
        takeSemaphore = new Semaphore(c.size(), true);
    }

    public T poll() {
        if (!takeSemaphore.tryAcquire()) {
            return null;
        }
        return queue.poll();
    }

    public T poll(long millis) throws InterruptedException {
        if (!takeSemaphore.tryAcquire(millis, TimeUnit.MILLISECONDS)) {
            return null;
        }
        return queue.poll();
    }

    public T take() throws InterruptedException {
        takeSemaphore.acquire();
        return queue.poll();
    }

    public void add(T t) {
        queue.add(t);
        takeSemaphore.release();
    }

    public static void main(String[] args) throws Exception {
        FairBlockingQueue<Object> q = new FairBlockingQueue<Object>();
        Object o = q.poll();
        assert o == null;
        o = q.poll(1000);
        assert o == null;

        q.add(new Object());
        q.add(new Object());
        q.add(new Object());

        o = q.take();
        assert o != null;
        o = q.poll();
        assert o != null;
        o = q.poll(1000);
        assert o != null;

        o = q.poll();
        assert o == null;
    }
}

可以为SynchronousQueue指定公平政策:

将fairness设置为true构造的队列以FIFO顺序授予线程访问权限

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM