Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand the mechanics of a synchronous queue

I was trying to read the implementation of Synchronous Queue
It is not so straightforward for me. It seems to be using a linked list where each node is associated with a thread.
And the core part uses a spin loop waiting for tasks to be placed in the queue.
I was wondering why is a spin loop being used instead of something like wait/notify?
Now this way one of the cores is gone due to this constant spin loop, right?
I am trying to understand this point and get a rough understanding of the design of the Synchronous Queue

UPDATE
What is also troubling me is how the waiter threads start/stop.

like image 221
Jim Avatar asked Aug 26 '13 21:08

Jim


1 Answers

The point of the SynchronousQueue is to synchronize something which is usually quite asynchronous - one thread placing an item into the queue while another tries to take from it.

The SynchronousQueue is actually not a queue at all. It has no capacity, no internal storage. It only allows taking from the queue when another process is currently trying to put in the queue.

Example:

Process A tries to put in the queue. This blocks for now. Process B tries to take from the queue. Since someone is trying to put, the item is transferred from A to B, and both are unblocked.

Process B tries to take from the queue, but no one tries to put. So B is now blocked. Process A now wants to put an item. Now the item is transferred over to B, and A and B are no longer blocked.

About the blocking:

The Sun/Oracle JRE implementation does use polling instead of a wait/notify pattern if you do a timed operation (like "try to take for 1 second"). This makes sense: it periodically retries until the time is up. When you do a non-timed operation (like "take, no matter how long it takes" it does use park, which wakes again if the situation has changed. In neither situation would one of your cores be constantly busy spinning a loop. The for (;;) means "retry indefinately" in this case, it does not mean "constant spinning".

like image 190
Jan Dörrenhaus Avatar answered Sep 21 '22 01:09

Jan Dörrenhaus