RE: JavaMemoryModel: correct synchronization

From: David Holmes (dholmes@dltech.com.au)
Date: Sun Feb 22 2004 - 21:44:16 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?

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.

I thought that one of the changes of the new JMM was that it localised the
effects of monitors that were previously global. Consequently I would have
naively expected only writes within a sync block to be guaranteed visible,
not necessarily writes before the sync block. But recalling some of the
slides I remember now that the memory affects for the release of the monitor
encompass everything that comes before the release.

So while the example is correctly synchronized by the definition, it is
non-intuitively correctly synchronized in my view. I really would hate to
start seeing people writing "clever" code this way. The non-use of direct
sync isn't even an optimisation in this case as far as I can see - and the
program would behave no differently if the accesses to w were moved to
inside the sync blocks.

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

Cheers,
David Holmes

-------------------------------
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