JavaMemoryModel: JMM problems with latch or copy-on-write?

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Wed Mar 28 2001 - 14:50:57 EST


> Hello. The problems with the JMM are pretty confusing. Basically what I
> know is to try not to avoid synchronization. But, there must be /some/
> techniques that are okay to do. Two that come to mind are:
> (1) A latch. If you've got a boolean in a class called something like
> "initialized" that begins being false and is eventually true forever... I
> assume that another thread will /eventually/ see that it is initialized in a
> reasonably small amount of time even though there is no explicit memory
> barrier.

Not necessarily. If the boolean is allocated to a register in the other
thread, and never removed from that register, then the other thread may
never see the initialization. Alternatively, it is possible for the
compiler to detect that the boolean is never changed, and then to
optimize away its reload. Consider:

boolean stop = false;

thread 1:
while (!stop)
{
  // do something
}

thread 2:

stop = true;

It would be perfectly reasonable for a compiler either to allocate stop
in a register in thread 1 (in which case it may never reread the stop's
location in memory). More realistically, it could perform an analysis
that showed that stop never changes, and optimize it to:

if (!stop)
  while (true)
    // do something

Because a goto is faster than a branch-if-true. To achieve your goal,
stop should be a volatile variable. Well, it should be if anyone
actually implemented them reasonably. Until they do, you might have to
use synchronization to guarantee your goals... Depends on the VM and
the architecture.

> (2) Copy on write. Again, I assume that another thread will /eventually/
> see the new reference to whatever was replaced in a reasonably small amount
> of time even though there is no explicit memory barrier.

Again, the same arguments apply. It is a little trickier to do these
optimization realistically with copy-on-write, but they can still be
done. You probably get the general idea. Fortunately, volatile
variables would help here too.

> Am I on the right track here or am I delusional? :-/

Sorry :)

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



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