Re: JavaMemoryModel: correct synchronization

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Sat Feb 21 2004 - 00:15:26 EST


> Hello,
> The reason I had doubts is that the JMM only talks about the program
> behavior with respect do shared data accesses. Th JMM does not even
> mention other language constructs like conditionals or loops. It seemed to
> me that it should be possible to determine if a program is correctly
> synchronized without analyzing effects that these other language
> constructs have on the execution of a program. This however is not the
> case in the example being discussed.
>
> What I was trying to achieve was to try to come up with a rule that a
> programmer could follow to write race-free concurrent programs. It seems
> to me that a sufficient condition is to protect every access to a shared
> variable by the same monitor (unless all the accesses are reads). Is
> that correct?

Yes.

> Then I was trying to determine if this is also a necessary condition, and
> that does not seem to be true, as the example indicates.

It is not a necessary condition. Correct.

In more detail, a data race is defined as two accesses to the same
variable, when at least one of them is a write, and they are not ordered
by what we call a "happens-before" relationship.

A happens-before relationship is defined in the documents on line.
Basically, we say there is a happens-before relationship between:

 An action followed by another in the same thread.
 An unlock followed by a lock on the same monitor.
 A volatile write followed by a volatile read of the same variable.
 (and some other stuff)

Since there must be a happens-before relationship between the write to w
and the unlock of M in Thread 1, a happens-before relationship between the
unlock of M in Thread 1 and the lock of M in Thread 2, and a
happens-before relationship between the lock of M in Thread 2 and the read
of w, there can be no data race in this program.

Basically, a program that can have no data races (without worrying about
potential reordering) is correctly synchronized.

Your rule of thumb should be, as long as all your accesses to shared
variables must be ordered by a happens-before relationship, there are no
data races in your program.

I've left out some details, but that's the gist of it. I hope that helps.

                                        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