spring-data-redis
module contains RedisAtomicLong
class.
In this class you can see
public boolean compareAndSet(long expect, long update) {
return generalOps.execute(new SessionCallback<Boolean>() {
@Override
@SuppressWarnings("unchecked")
public Boolean execute(RedisOperations operations) {
for (;;) {
operations.watch(Collections.singleton(key));
if (expect == get()) {
generalOps.multi();
set(update);
if (operations.exec() != null) {
return true;
}
}
{
return false;
}
}
}
});
}
My question is why it works?
generalOps.multi()
starts transaction after get()
is invoked. It means that there is possibility that two different thread (or even client) can change value and both of them will succeed.
Is operations.watch
prevent it somehow? JavaDoc doesn't explain purpose of this method.
PS: Minor question: why for (;;)
? There is always one iteration.