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

Bill Pugh pugh at cs.umd.edu
Sat Jun 11 06:33:55 EDT 2005


The first implementation is legal.
It should even work fine for longs and primitives
in Sun's 1.4 JVM.

The one with the unsynchronized lazySet is broken. Don't use it.

     Bill Pugh



On Jun 11, 2005, at 12:21 AM, Dawid Kurzyniec wrote:
> 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; }
>    synchronized void lazySet(int newVal) { val = newVal; }
>    synchronized int getAndIncrement() { return value++; }
>    synchronized int compareAndSet(int expect, int update) {
>        boolean success = (expect == value);
>        if (success) value = update;
>        return success;
>    }
>    // etc.
> }
>
> And then, is the above legal (I guess not, since read-writes still  
> need to be atomic with respect to lazySet):
>
> 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.
> }
>
>
> Of course I realize that these hacks are definitely not allowed for  
> longs and non-primitives.
>
> Regards,
> Dawid
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>



More information about the Concurrency-interest mailing list