Re: finitequeue heavy synchronization

Miles Sabin <[email protected]> Fri, 5 Sep 2003 19:56:15 +0100
Newsgroups gmane.comp.java.seda.user
Message-ID <[email protected]>
Quartz wrote,
> The caller has no protection on the sanity of the queue size, once
> received, because it is not synchronized anymore. And given that
> queue size is an int, not a long, java garantees atomic assigment.

The only relevant guarantee here is that there won't be any "word- 
tearing" (cp. long and double).

> So this size method requires no synchronization in my opinion.
>
>   /**
>    * Return the size of the queue.
>    */
>   public int size() {
>     synchronized(blocker) {
>       synchronized(qlist) {
> 	return queueSize;
>       }
>     }
>   }

<snip/>

> Any reason why I shouldn't remove synchronization? What is the
> "blocker" critical zone semantic?

The blocker is that writes to queueSize from one thread won't 
necessarily be visible to reads from another unless there have been 
intervening synchronization operations of some kind. The release of a 
lock by the writer followed by an acquire of the same lock by the 
reader is one way of achieving that. In principle making queueSize 
volatile would also do the trick, but very few implementations of 
volatile semantics have been correct until quite recently, so the use 
of synchronization is the safer bet from a portability POV.

Lots of people find this behaviour surprising, so I should point out 
that it's not just theoretical: inter-thread visibility issues are very 
real on multiprocessors, and are not unheard of even on uniprocessors.

For much more info I recommend taking a peek at section 2.2 of Doug 
Lea's Concurrent Programming in Java, which is available online at,

  http://gee.cs.oswego.edu/dl/cpj/jmm.html

If you're feeling adventurous, have a browse around here,

  http://www.cs.umd.edu/~pugh/java/memoryModel/

which is the primary source of info on the rationale for and current 
state of JSR-133 which is revising and clarifying the Java memory model 
for Tiger.

Cheers,


Miles


-------------------------------------------------------
This sf.net email is sponsored by:ThinkGeek
Welcome to geek heaven.
http://thinkgeek.com/sf