Java – compare and exchange
As the title indicates, I am looking for a comparison and exchange implementation, but it is relatively large:
if(newValue > oldValue) {
oldValue = newValue;
}
Where oldvalue is some global shared state, and newvalue is private to each thread without doing so:
synchronized(locker) {
if(newValue > oldValue) {
oldValue = newValue;
}
}
Because I want a non blocking solution From studying the source code of other non blocking operations, I have proposed this point (assuming that the value is an integer):
AtomicInteger oldValue; // shared global variable
...
public boolean GreaterThanCAS(int newValue) {
while(true) {
int local = oldValue;
if(local == oldValue) {
if(newValue > local) {
if(oldValue.compareAndSwap(local,newValue) {
return true; // swap successful
} // else keep looping
} else {
return false; // swap Failed
}
} // else keep looping
}
}
When the / / else hold loop occurs, it means that another thread changed the oldvalue during this period, so I need to loop and try again
Is this implementation correct (thread safe)?
Solution
If there is no thread to reduce the value of atomicinteger, I think there is no problem with your implementation If they do, your code is a competitive condition
Note that the code can be simplified as follows:
public boolean GreaterThanCAS(int newValue) {
while(true) {
int local = oldValue.get();
if(newValue <= local) {
return false; // swap Failed
}
if(oldValue.compareAndSwap(local,newValue)) {
return true; // swap successful
}
// keep trying
}
}
