[concurrency-interest] Reader-writer visibility in LinkedBlockingQueue

Ashwin Jayaprakash ashwin.jayaprakash at gmail.com
Thu Aug 15 22:36:11 EDT 2013


Hi, I have a (naive) question about the JDK 7+ LinkedBlockingQueue
implementation.

(I don't think this question has been asked before. I did search
here<http://markmail.org/search/?q=concurrency%20interest%20linkedblockingqueue#query:concurrency%20interest%20linkedblockingqueue+page:15+mid:ocig5f7ry2j5emhl+state:results>before
deciding to use your time. I think the answer is evident but just
need a confirmation)

In the source comment
here<http://www.grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/concurrent/LinkedBlockingQueue.java#97>it
says:

Visibility between writers and readers is provided as follows:
>
> Whenever an element is enqueued, the putLock is acquired and
> count updated.  A subsequent reader guarantees visibility to the
> enqueued Node by either acquiring the putLock (via fullyLock)
> or by acquiring the takeLock, and then reading n = count.get();
> this gives visibility to the first n items.
>

My understanding of the code:

   1. I noticed that the Node.next
   <http://www.grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/concurrent/LinkedBlockingQueue.java#120>is
   not marked volatile
   2. The dequeue thread always acquires the takeLock. The only time
it acquires,
   signals and quickly releases the
putLock<http://www.grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/concurrent/LinkedBlockingQueue.java#181>is
when the queue has room for just 1 more item before becoming full
again
   3. The enqueue thread does the opposite of the dequeue
   4. So, except for the edge cases (recently full/recently empty) where
   the reader and writer acquire and notify each other, how does the enqueue
   of a new node (Node.next) become visible to the dequeue?

Pardon my ignorance but does this mean that:

   1. 2 threads that acquire 2 independent locks are enough to make the
   "next" pointer visible?
   2. Or is it the AtomicInteger's count.inc/dec that is providing the
   desired memory effect? *I think this is it, but I'm seeking clarification
   *


Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20130815/368499ed/attachment.html>


More information about the Concurrency-interest mailing list