[concurrency-interest] Min and Max for Atomics

Nathan and Ila Reynolds nathanila at gmail.com
Thu Aug 10 13:35:50 EDT 2017


Yes, I get the same behavior, but I will have to pay for a cache 
invalidation, CAS and a memory fence with each call.  For example, if I 
am tracking a high-water mark then at the beginning the updates should 
be very often and then taper off to nothing.  Thus, over time the cost 
is reduced to a load from cache or RAM.

-Nathan

On 8/10/2017 10:15 AM, Jonas Konrad wrote:
> Note that you can achieve the same behaviour using updateAndGet(i -> 
> Math.max(i, newVal)), at the cost of one CAS even on keeping the 
> current value.
>
> Looking at it, the shortcut prev == next could be taken in 
> updateAndGet too. Maybe it can't because you need the HB semantics of 
> compareAndSet?
>
> - Jonas Konrad
>
>
> On 08/10/2017 01:51 PM, Nathan and Ila Reynolds wrote:
>> 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
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

-- 
-Nathan



More information about the Concurrency-interest mailing list