Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Better AtomicLong and AtomicInteger in Java

DZone's Guide to

Better AtomicLong and AtomicInteger in Java

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

 I was always annoyed by the fact that AtomicLong.compareAndSet(...) method in Java only checked for exact equality. What if you need to check if the value is less than or greater than? So I finally just created my own AtomicLong and AtomicInteger classes and added them to GridGain utilities to be used by us and by all our users.

The code is very simple:

public class MyAtomicLong extends AtomicLong {
    public boolean greaterAndSet(long check, long update) {
        while (true) {
            long cur = get();

            if (check > cur) {
                if (compareAndSet(cur, update))
                    return true;
            }
            else
                return false;
        }
    }

    public boolean greaterEqualsAndSet(long check, long update) {
        while (true) {
            long cur = get();

            if (check >= cur) {
                if (compareAndSet(cur, update))
                    return true;
            }
            else
                return false;
        }
    }

    public boolean lessAndSet(long check, long update) {
        while (true) {
            long cur = get();

            if (check < cur) {
                if (compareAndSet(cur, update))
                    return true;
            }
            else
                return false;
        }
    }

    public boolean lessEqualsAndSet(long check, long update) {
        while (true) {
            long cur = get();

            if (check <= cur) {
                if (compareAndSet(cur, update))
                    return true;
            }
            else
                return false;
        }
    }
}

Based on the comments I received, I have also added predicate-based 'checkAndSet(...)' method:

    public boolean checkAndSet(GridPredicate<Long> p, long update) {
        while (true) {
            long cur = get();

            if (p.apply(cur)) {
                if (compareAndSet(cur, update))
                    return true;
            }
            else
                return false;
        }
    }

Of course in GridGain these classes are named GridAtomicInteger and GridAtomicLong, since we prefix all our classes with the word Grid.

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

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}