What i need to know is the correctness of the following getters / setters. Are they completely thread-safe? If not, in which case are they not thread-safe? Any remarks about behaviour are welcome, thanks guys π
The code is in java, but the logic applies to any language that supports CAS and objects.
private Object obj; private AtomicLong version = new AtomicLong(0); private AtomicBoolean isUpdating = new AtomicBoolean(false); public Object get() { long before = version.get(); while (true) { Object obj = this.obj; long after = version.get(); if (before == after && before % 2 == 0) return obj; before = after; } } public void set(Object obj) { while (!isUpdating.compareAndSet(false, true)) { //spin } version.getAndIncrement(); this.obj = obj; version.getAndIncrement(); isUpdating.set(false); }