Java SynchronousQueue example

Java SynchronousQueue class is the only collection object which does not have any internal memory capacity. That's the beauty of this collection class and thus many fellow use to ask this in interview question about which Java collection class has no memory capacity? (Answer)

Now you might be wondering if it has no memory capacity, not even of one, then how come this collection framework is even working and how can anyone use it?

First of all, Synchronous Queue comes under the class of Blocking Queue i.e. it has all the features of Blocking Queue
Hence it works by putting the insert operation thread to wait for remove operation by another thread. In other words, the thread inserting element to Synchronous Queue gets blocked till another thread takes the element out and vice-versa. That means any thread tries to take out the element will get blocked if there is no another thread to put the element into the queue. So the thread which tries to put the element (and gets blocked until there is no taker) keeps hold of the element on its behalf and thus the queue size is always zero (no memory capacity of its own).

Real Time Example:
The best way to understand SynchronousQueue  is the ping-pong game, where a person passes the ball to another. Consider there are many persons and many balls for this ping-pong game. So here each person holding the ball is passing it to another person and that another person is passing to someone else and it goes on. 
In the above example, each person is a separate thread and ball is an element and it passes via Synchronous Queue. It is quite worthy to note that while Person A is passing the ball to Person B, it doesnot put the ball into any basket (Synchronous queue here) but passes directly to person B and thus the queue doesn't need to hold that ball element. So with this way N persons holding N balls blocks until another N another persons receives it.

How SynchronousQueue works internally:

When a thread put the element on Synchronous Queue, internally that thread goes to wait state on SynchronousQueue Object and when another thread take the element from the queue, it internally calls notify to SynchronousQueue Object leading to one waiting thread thread to wake up. You can also think Synchronous Queue as advanced way for Object wait() and notify() method. SynchronousQueue Object smartly uses Object's monitor lock feature to achieve this.

No comments:

Post a Comment