Greater-than compare-and-swap
Since Java 8 this can be simplified with use of updateAndGet:
public boolean greaterThanCAS(int newValue) { return oldValue.updateAndGet(x -> x < newValue ? newValue : x) == newValue;}
Note that this would return true also in case when old and new values are equal.Give a try to @Adam's answer if this is not desired behaviour.
I see no problems with your implementation, provided that no thread ever decreases the value of the AtomicInteger
. If they do, your code is open to race conditions.
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.compareAndSet(local, newValue)) { return true; // swap successful } // keep trying }}
I would re write it to look more like:
while(true) { int local = oldValue.get(); if(newValue > local){ if(oldValue.compareAndSwap(local, newValue) { return true; // swap successful } // else keep looping }else return false; }
The equivalence check before the greater than check is redundant.
Otherwise it should work fine.