SynchronousQueue which is an implementation of the BlockingQueue interface was added in Java 5 along with other concurrent utilities like ConcurrentHashMap, ReentrantLock, Phaser, CyclicBarrier etc.
How SynchronousQueue differs from other implementations of BlockingQueue like ArrayBlockingQueue and LinkedBlockingQueue is that SynchronousQueue in Java does not have any internal capacity, not even a capacity of one. In SynchronousQueue each insert operation must wait for a corresponding remove operation by another thread, and vice versa.
What that means is, if you put an element in SynchronousQueue using put() method it will wait for another thread to receive it, you can't put any other element in the SynchronousQueue as it is blocked. Same way in case there is thread to remove an element (using take() method) but there is no element in the queue it will block and wait for an element in the queue.
Java SynchronousQueue differs in functionality
Since SynchronousQueue has a very special functionality which differs from other BlockingQueue implementations so methods in Java SynchronusQueue behave a little differently. Actually calling it a Queue itself is a bit of wrong statement as there is never more than one element present. It's more of a point-to-point handoff.
As an example take peek() method, which in other BlockingQueue implementations work as follows-
peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
Since in SynchronousQueue an element is only present when you try to remove it so peek() method in this class always returns null.
Iterator in SynchronousQueue returns an empty iterator in which hasNext always returns false.
For purposes of other Collection methods a SynchronousQueue acts as an empty collection, so methods like
- contains- Always returns false. A SynchronousQueue has no internal capacity.
- remove- Always returns false. A SynchronousQueue has no internal capacity.
- isEmpty()- Always returns true. A SynchronousQueue has no internal capacity.