[concurrency-interest] What does it mean to synchronize "return x;" ?

jws@cs.mu.OZ.AU jws@cs.mu.OZ.AU
Thu, 15 Jul 2004 09:06:50 +1000

> I was looking at some code last night that did the following.
> I was wondering - is there anything special about synchronizing a critical
> section of code that is a return statement?
>    private int curr;
>    private double []hArray;
>             synchronized(hArray)
>             {
>                 return hArray [curr];
>             }

Non-volatile double (and long) values are not atomic in Java on
all processors.  (JLS 17.4)  So, if the array element may possibly be
written concurrently with reading it then some form of mutual exclusion
is required to ensure that either the old, or the new value is read and
not part of each.

(There is also additional coordination being imposed on accesses to curr,
but that said, the rest of the code snippet has the markings of having
chosen the wrong object to control access.)

    Jeff Schultz