3 ms·
Can't the ABA problem circumvented quite easily by making the shared state immutable? Every modification will create a new instance, like so (in JAVA): class
by Phelinofist 2y ago
Can't the ABA problem circumvented quite easily by making the shared state immutable? Every modification will create a new instance, like so (in JAVA):
class State {
private int value;
private String anotherValue;
State(int value, String anotherValue) {
this.value = value;
this.anotherValue = anotherValue;
}
State changeValue(int newValue) {
return new State(newValue, anotherValue);
}
// same for anotherValue
}
AtomicReference<State> state = new AtomicReference<>(new State(1, "a");
State oldState;
State newState;
for(;;) {
oldState = this.state.get();
newState = oldState.changeValue(2);
if(this.state.compareAndSet(oldState, newState)) {
break;
}
}
Since object identity is used for comparison, and every transition is a new object, the ABA problem cannot happen because - even if the state are equal - the comparison will fail.
- whizzter 2y agoIn Java if you hold an reference to an "old" object then that will be kept alive until all references are exhausted, thus an identity comparison comparing pointers will never succeed as long as someone holds an reference (that is compared to). In languages with more manual management, the pointer itself if used can be reused and succeed in bad cases (though from my cursory knowledge of Rust this seems to indicate quite a bit of unsafe behaviours).
- wat10000 2y agoThe problem isn’t the mutability of the State object, but the mutability of the pointer to it. Your approach works in Java, but it only works if you have a garbage collector that can ensure the memory is not freed until there are no extant pointers to it, or you never free the objects. The ABA problem occurs when one writer reads the old pointer, another writer swaps out the pointer and frees the old object, a third writer allocates a new object that happens to be placed at the exact same location as the first one, then the first writer does its compare-and-swap.
- gpderetta 2y agoIn any language with GC, a lot of complex concurrency problems become much simpler (but of course now you have to deal with the GC).