且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该在 Java 中使用哪个并发队列实现?

更新时间:2023-11-23 16:48:58

它们之间的区别基本上是性能特征和阻塞行为.

Basically the difference between them are performance characteristics and blocking behavior.

先取最简单的,ArrayBlockingQueue是一个固定大小的队列.因此,如果您将大小设置为 10,并尝试插入第 11 个元素,则插入语句将阻塞,直到另一个线程删除一个元素.公平问题是如果多个线程同时尝试插入和删除(换句话说,在队列被阻塞期间)会发生什么.公平算法确保第一个请求的线程是第一个获得的线程.否则,给定线程可能会比其他线程等待更长的时间,从而导致不可预测的行为(有时一个线程只需几秒钟,因为稍后启动的其他线程首先得到处理).代价是管理公平性需要开销,从而降低吞吐量.

Taking the easiest first, ArrayBlockingQueue is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.

LinkedBlockingQueueConcurrentLinkedQueue 之间最重要的区别是,如果您从 LinkedBlockingQueue 请求元素并且队列为空,则您的线程会等到那里有东西.ConcurrentLinkedQueue 将立即返回一个空队列的行为.

The most important difference between LinkedBlockingQueue and ConcurrentLinkedQueue is that if you request an element from a LinkedBlockingQueue and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue will return right away with the behavior of an empty queue.

哪一个取决于你是否需要阻塞.在你有许多生产者和一个消费者的地方,听起来很像.另一方面,如果您有许多消费者而只有一个生产者,您可能不需要阻塞行为,并且可能很乐意让消费者检查队列是否为空,如果是则继续前进.

Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.