[concurrency-interest] concurrency puzzle

Jeremy Manson jmanson at cs.umd.edu
Tue Sep 12 15:29:35 EDT 2006


Peter Veentjer wrote:
> I you look at the following documentation:
> 
> http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#volatile
> 
> They talk about cache invalidation:
> if a lock is obtained, the cache is invalidated.
> 
> So occording to this documentation, the write x=20 could get lost if
> it isn't flushed to main memory and this makes 0 a possible output
> value.
> 
> So what should I believe?

Both of us! :)

(Actually, it is only one of us, technically.  Well, two, because Brian 
co-wrote it.)

I believe that you were concerned about the following example:

x = 20;
synchronized (this) {
   print x;
}

You were worried that the write to x would be in the cache, but that the 
print would be from the value in main memory.  However, that's not how 
cache coherence works.  To simplify, what will happen is that the write 
to x will occur, and subsequent reads of x from the same processor will 
either

a) be taken from the cache (and return 20), or

b) be taken from main memory, *after the values in the cache are written 
out to it* (and return 20, or some other value that was written out 
after the 20 -- this might include the 10 from the other thread).

The paragraph to which you point is just saying that reads of volatiles 
have to be of type b), so that they see any writes to that volatile that 
might have been performed by another processor.  Otherwise, they might 
see stale cache values.

I hope that helps a little.

						Jeremy


More information about the Concurrency-interest mailing list