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

Dawid Kurzyniec dawidk at mathcs.emory.edu
Sat Jun 11 00:21:08 EDT 2005


I am trying to optimize some algorithms in the backport-util-concurrent. 
Currently, backported atomics are written defensively:

public class AtomicInteger {
    int val;
    synchronized int get() { return val; }
    synchronized void set(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.
}

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



More information about the Concurrency-interest mailing list