[concurrency-interest] Min and Max for Atomics

Nathan and Ila Reynolds nathanila at gmail.com
Thu Aug 10 07:51:12 EDT 2017


Have the following methods been considered to be added to their 
respective classes?  Perhaps, there are other Atomic classes where these 
should be added.  Perhaps, VarHandles should have these added (assume I 
know nothing about VarHandles).

The advantage of these methods is that they avoid cache invalidation and 
a fence if there is no update.  This is kind of related to the previous 
discussion about getAndUpdate() and updateAndGet().

I am proposing these methods since I have written this code a few 
times.  Until these methods are implemented in the JDK, perhaps I should 
write an atomic utility class.

AtomicInteger

public int max(int value)
{
    int expect;

    while (true)
    {
       expect = get();

       if (expect >= value)
          return expect;

       if (compareAndSet(expect, value))
          return expect;
    }
}

public int min(int value);
{
    int expect;

    while (true)
    {
       expect = get();

       if (expect <= value)
          return expect;

       if (compareAndSet(expect, value))
          return expect;
    }
}

AtomicLong
public long max(long value);
public long min(long value);


-- -Nathan


More information about the Concurrency-interest mailing list