Note that there are some explanatory texts on larger screens.

plurals
  1. POSynchronization of a Queue
    primarykey
    data
    text
    <p>I've been reading up on Doug Lea's 'Concurrency Programming in Java' book. As you may know, Doug originally wrote the Java Concurrency API. However, something has caused me some confusion and I was hoping to gain a few my opinions on this little conundrum!</p> <p>Take the following code from Doug Lea's queuing example...</p> <pre><code>class LinkedQueue { protected Node head = new Node(null); protected Node last = head; protected final Object pollLock = new Object(); protected final Object putLock = new Object(); public void put(Object x) { Node node = new Node(x); synchronized (putLock) { // insert at end of list synchronized (last) { last.next = node; // extend list last = node; } } } public Object poll() { // returns null if empty synchronized (pollLock) { synchronized (head) { Object x = null; Node first = head.next; // get to first real node if (first != null) { x = first.object; first.object = null; // forget old object head = first; // first becomes new head } return x; } } } static class Node { // local node class for queue Object object; Node next = null; Node(Object x) { object = x; } } } </code></pre> <p>This a quite a nice Queue. It uses two monitors so a Producer and a Consumer can access the Queue at the same time. Nice! However, the synchronization on 'last' and 'head' is confusing me here. The book states this is needed for for the situation whereby Queue is currently or about to have 0 entries. Ok, fair enough and this kind of makes sense. </p> <p>However, then I looked at the Java Concurrency LinkedBlockingQueue. The <a href="http://downloads.atlassian.com/software/clover/samples/backport-util-concurrent/edu/emory/mathcs/backport/java/util/concurrent/LinkedBlockingQueue.html#46" rel="nofollow noreferrer">original</a> version of the Queue don't synchronize on head or tail (I also wanted to post another link to the modern version which also suffers from the same problem but I couldn't do so because I'm a newbie). I wonder why not? Am I missing something here? Is there some part of the idiosyncratic nature of the Java Memory Model I'm missing? I would have thought for visibility purposes that this synchronization is needed? I'd appreciate some expert opinions!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload