Platinum Partner
java

Better AtomicLong and AtomicInteger in Java

 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

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}