Re: JavaMemoryModel: correct synchronization

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Sun Feb 22 2004 - 23:43:52 EST


> Bill Pugh wrote:
> > On Feb 20, 2004, at 5:16 PM, Adam Welc wrote:
> > >
> > >
> > > Is the following program correctly synchronized?
> > >
> > >
> > > public static boolean w = false;
> > > public static boolean v = false;
> > >
> > > T1 T2
> > > w=true; while(true) {
> > > synchronized(M) { synchronized(M) {
> > > v =true; if (v) break;
> > > } }
> > > }
> > > boolean tmp=w;
> >
> > Unless I'm missing something, this program is correctly synchronized.
> > ...
> > What makes you think this program may not be correctly synchronized?

This first:

> In short I wish this were not correctly synchronized so that I could easily
> justify telling people not to do it. ;-)

You can tell people not to do it because this is a bad, inefficient,
potentially-breaking-on-fairness-guarantees way to reimplement wait and
notify. "Correct" code isn't necessarily good code.

> Well it is somewhat counter-intuitive that the use of w is correctly
> synchronized given that access to w is not protected by a monitor, nor is w
> volatile, or protected by a volatile. This breaks the basic "concurrency
> 101" rule for stating how to write a correctly synchronized program.

Here's the concurrency 101 rule we've been using: if two accesses are
guaranteed to be ordered by synchronization actions, they aren't in a data
race.

This is useful if you are programming something like a handoff of an
object between threads (when only a single thread at a time will access
it). As long as the actual handoff part is synchronized, you don't need
to synchronize access to the actual object, even though it is shared.

"Better to use a volatile" doesn't quite cut it in some cases, because
there may need to be some bookkeeping in shared memory.

I think this is reasonable. Except that they should have used wait and
notify, and not stuck a loop in Thread 2.

                                        Jeremy
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:58 EDT