As the title suggests, I'm looking for a compare-and-swap implementation, but with greater-than comparison:
if(newValue > oldValue) {
oldValue = newValue;
}
where oldValue
is some global shared state and newValue
is private to each thread, without doing this:
synchronized(locker) {
if(newValue > oldValue) {
oldValue = newValue;
}
}
because I want a non-blocking solution. From studying source codes of other non-blocking operations, I've come up with this (assuming the values are integers):
AtomicInteger oldValue; // shared global variable
...
public boolean GreaterThanCAS(int newValue) {
while(true) {
int local = oldValue;
if(local == oldValue) {
if(newValue > local) {
if(oldValue.compareAndSet(local, newValue) {
return true; // swap successful
} // else keep looping
} else {
return false; // swap failed
}
} // else keep looping
}
}
when // else keep looping
happens, it means that another thread has changed the oldValue
in the meantime and so I need to loop and try again.
Is this implementation correct (thread-safe)?
local
variable and checking to see if they're the same. Thread switching could occur after your if statement. So no, this is not thread safe, but without blocking I'm not sure if you'll find a solution. – FuruncleoldValue.compareAndSwap(local, newValue)
call also returns false if theoldValue
is not equal tolocal
, so it also checks here. – OsmenputIfGreater
or something would be a better method name. – TriremeoldValue
is a very strange name. Hope it isn't really global.) – Trireme