Last week I blogged about "Better AtomicInteger and AtomicLong in Java" and how I added it to GridGain 'lang.utils' package to be used within GridGain project and by our user base. Recently I made it even better. The standard JDK atomic 'compareAndSet(..)' operations always check for some 'expected' value and if it matches, then the set happens. What if you simply want to set a value if its greater or less than current value, or if it simply does not match the current value?
Again, code looks pretty simple:
Again, code looks pretty simple:
public class MyAtomicInteger extends AtomicInteger { ... // Omitting methods from previous blog public boolean setIfGreater(int update) { while (true) { int cur = get(); if (update > cur) { if (compareAndSet(cur, update)) return true; } else return false; } } public boolean setIfGreaterEquals(int update) { while (true) { int cur = get(); if (update >= cur) { if (compareAndSet(cur, update)) return true; } else return false; } } public boolean setIfLess(int update) { while (true) { int cur = get(); if (update < cur) { if (compareAndSet(cur, update)) return true; } else return false; } } public boolean setIfLessEquals(int update) { while (true) { int cur = get(); if (update <= cur) { if (compareAndSet(cur, update)) return true; } else return false; } } public boolean setIfNotEquals(int update) { while (true) { int cur = get(); if (update != cur) { if (compareAndSet(cur, update)) return true; } else return false; } } }
View comments