[concurrency-interest] concurrency puzzle

David Holmes dcholmes at optusnet.com.au
Sun Sep 10 19:22:20 EDT 2006


Peter,

Some confusion seems to have arisen.

>    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)

In the absence of any other methods that write to x then the value of x is
always 20 when the println is invoked. It is irrelevant whether the write to
x is visible to some other thread at that time as no other thread has access
to x. Any thread that executes foo() will do the assignment x=20 and then
print out the value 20 because in program order the write to x
happens-before the read of x used by the println.

It would be a different matter if there was a seperate setter method that
could be called. I think you need to reconsider your example.

Cheers,
David Holmes



More information about the Concurrency-interest mailing list