[concurrency-interest] is "volatile read / synchronized write" legal?

Doug Lea dl at cs.oswego.edu
Sat Jun 11 06:34:06 EDT 2005


Dawid Kurzyniec wrote:
> I am trying to optimize some algorithms in the backport-util-concurrent. 

> 
> But the following is tempting. Is it valid and safe to use in Java <= 
> 1.4? And if not, why:
>
> public class AtomicInteger {
>     volatile int val;
>     int get() { return val; } // not synchronized
>     synchronized void set(int newVal) { val = newVal; }
>     void lazySet(int newVal) { val = newVal; } // not synchronized
>     synchronized int getAndIncrement() { return value++; }
>     synchronized int compareAndSet(int expect, int update) {
>         boolean success = (expect == value);
>         if (success) value = update;
>         return success;
>     }
>     // etc.
> }
> 

This would be OK on JVMs that correctly implement the JMM
volatile spec. No pre-J2SE5 JVM promises to do so, but in
practice Sun 1.4+ JVMs correctly handle this particular usage.
"Volatile" was not implemented at all on
IBM JVMs until, I think, 1.4.1 (I could be wrong).
Similarly, I think, for jrockit.
And I don't know about others.

So, in general, this has a chance of being OK on most 1.4.1+
JVMs. Definitely not on most earlier ones. All in all,
probably not worth doing.

-Doug


More information about the Concurrency-interest mailing list