[concurrency-interest] Volatile happens before question

Raph Frank raphfrk at gmail.com
Wed Jan 18 07:10:02 EST 2012


Another question, would this work properly as a lock?

public class OptimisticLockInt {

    private int x;
    private AtomicInteger counter = new AtomicInteger(0);
    private static final int UNSTABLE = 1;

    public void set(int x)
        int oldCount = counter.getAndSet(UNSTABLE);
        this.x = x;
        counter.set(oldCount + 2);
    }

    public int get() {
        while (true)
            int oldCount = counter.getAndSet();
            int tempX = x;
            if (counter.get() == oldCount) {
                return tempX;
            }
        }
    }
}

I guess the get() method can be reordered to the following?

    public int get() {
        while (true)
            int oldCount = counter.getAndSet();
            if (counter.get() == oldCount) {
                int tempX = x;
                return tempX;
            } else {
                int tempX = x;
            }
        }
    }

If so, what is the best way to do optimistic locking?


More information about the Concurrency-interest mailing list