new SynchronousQueue()
new LinkedBlockingQueue(1)
What is the difference? When I should use SynchronousQueue
against LinkedBlock
[Just trying to put it in (possibly) more clearer words.]
I believe the SynchronousQueue API docs states things very clearly:
- A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa.
- A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to remove it; you cannot insert an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate.
- The head of the queue is the element that the first queued inserting thread is trying to add to the queue; if there is no such queued thread then no element is available for removal and
poll()
will returnnull
.
And BlockingQueue API docs:
- A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
So the difference is obvious and somewhat critically subtle, especially the 3rd point below:
BlockingQueue
, the operation block till the new element is inserted. Also, if the queue is full when you are inserting in the BlockingQueue
, the operation will block till the element is removed from the queue and a space is made for the new queue. However note that in SynchronousQueue
, as operation is blocked for opposite operation (insert and remove are opposite of each other) to occur on another thread. So, unlike BlockingQueue
, the blocking depends on the existence of the operation, instead of existence or non existence of an element.peek()
always returns null
(again, check the API doc) and iterator()
returns an empty iterator in which hasNext()
always returns false
. (API doc). However, note that the poll()
method neatly retrieves and removes the head of this queue, if another thread is currently making an element available and if no such thread exists, it returns null
. (API doc)Finally, a small note, both SynchronousQueue
and LinkedBlockingQueue
classes implement BlockingQueue
interface.