Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between BlockingQueue and TransferQueue

I am a little bit confused as to what the difference is between BlockingQueue/LinkedBlockingQueue and the new TransferQueue/LinkedTransferQueue types from jsr166y and java 7

like image 306
jvdneste Avatar asked Sep 06 '11 09:09

jvdneste


People also ask

What is BlockingQueue used for?

BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

What is TransferQueue in Java?

The TransferQueue interface is a member of the Java Collections Framework. It was introduced in JDK 1.7, it belongs to java. util. concurrent package. The TransferQueue is a BlockingQueue in which a sending thread(producer) may wait for the receiving thread(consumers) to receive elements.

Is Java BlockingQueue thread safe?

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.


1 Answers

From TransferQueue JavaDocs:

A BlockingQueue in which producers may wait for consumers to receive elements. A TransferQueue may be useful for example in message passing applications in which producers sometimes (using method transfer(E)) await receipt of elements by consumers invoking take or poll, while at other times enqueue elements (via method put) without waiting for receipt.

In other words, when you use BlockingQueue, you can only put element into queue (and block if queue is full). With TransferQueue, you can also block until other thread receives your element (you must use new transfer method for that). This is the difference. With BlockingQueue, you cannot wait until other thread removes your element (only when you use SynchronousQueue, but that isn't really a queue).

Other than this, TransferQueue is also a BlockingQueue. Check out new available methods in TransferQueue: http://download.oracle.com/javase/7/docs/api/java/util/concurrent/TransferQueue.html (transfer, tryTransfer, hasWaitingConsumer, getWaitingConsumerCount).


Collections Framework Enhancements in Java SE 7 says explicitly:

The interface TransferQueue has been added. It is a refinement of the BlockingQueue interface in which producers can wait for consumers to receive elements. One implementation of the new interface is also included in this release, LinkedTransferQueue.

like image 61
Peter Štibraný Avatar answered Oct 14 '22 05:10

Peter Štibraný