Re: JavaMemoryModel: Synchronization and the Java Memory Model

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Tue Sep 02 2003 - 21:08:11 EDT


Hi Evan,

>
> Doug,
>
> Thanks for the clarification. I have already found the page
> http://www.cs.umd.edu/~pugh/java/memoryModel, in fact that is where I found
> the link to the document I quoted. I presume that by "new version" you are
> referring specifically to
> http://www.cs.umd.edu/~pugh/java/memoryModel/newest.pdf.

I strongly recommend that you look at the community review document:

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

This treats informal questions in a much clearer way than the newest.pdf
you looked at.

Having said that, the basic requirement you are after is that:

All writes that happen before a given unlock must be visible to any
actions that happen after a following lock of the same monitor.

So, in your example:

> synchronized (a)
> {
> synchronized (b)
> {
> p.x++;
> }
> }

You incremented p.x both before you unlocked b, and before you unlocked a.
Therefore, that write must be visible after a following lock on a OR b.
Either of these:

>
> synchronized (a)
> {
> // do something with p.x
> }
>
> or:
>
> synchronized (b)
> {
> // do something with p.x
> }

Is fine.

Synchronization operations on different monitors do not establish these
happens before paths. So, in:

Thread 1:
synchronized(a) {
  p.x++
}

Thread 2:
synchronized(b) {
  r1 = p.x;
}

Even if Thread 1 occurs earlier (in some sense) than Thread 2, Thread 1
does not "happen-before" Thread 2; Thread 2 is not guaranteed to see the
increment.

The way it works is a little different from the intuition you put in your
message. Does this intuition make it a little clearer?

                                        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:51 EDT