[concurrency-interest] concurrency puzzle

Peter Veentjer alarmnummer at gmail.com
Sun Sep 10 11:42:14 EDT 2006


I'm playing with the Java Memory Model documentation. And to check if
my understanding is correct, I'm interested in the following example:

public class A{
   private int x = 10;

   public void foo(){
      x = 20;
      synchronized(this){
         System.out.println( x );
      }
   }
}

If this class is used in a multithreaded environment, what could the
output be? (foo is called only once to make it easy)

20: if the x=20 is written to main memory, the read for println( x )
will return 20.

10: if x=20 isn't written to main memory, but only in local memory,
the write (x=20) could get lost. This is because the local memory is
invalidated when the lock on this is acquired. When x is read for the
println, it will return the value in main memory (and that is 10).

0: the 10 value doesn't need to be visible in main memory because it
isn't published safely. So for the same reasons 10 could be read for
the println, the default value for int (that is a 0) could be read for
the println.

0: a different thread could obtain a partially initialized reference
to A because of reordening. So 0 could be the value of x when it is
read for the println statement. So this is another way the 0 value
could be found.

So my bet would be

20 or 10 or 0.

Is my understanding correct?


More information about the Concurrency-interest mailing list