Over a million developers have joined DZone.
Silver Partner

Even Better AtomicLong and AtomicInteger in Java

· Java Zone

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:

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;
        }
    }
}

From http://gridgain.blogspot.com/2011/06/even-better-atomicinteger-and.html

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}