Java AtomicLong getAndAddCap(AtomicLongFieldUpdater updater, T instance, long n)

Here you can find the source of getAndAddCap(AtomicLongFieldUpdater updater, T instance, long n)

Description

Atomically adds the value to the atomic variable, capping the sum at Long.MAX_VALUE and returning the original value.

License

Apache License

Parameter

Parameter Description
T the type of the parent class of the field
updater the field updater
instance the instance of the field to update
n the value to add, n > 0, not validated

Return

the original value before the add

Declaration

public static <T> long getAndAddCap(AtomicLongFieldUpdater<T> updater,
        T instance, long n) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

public class Main {
    /**/*from www . ja  v  a  2s .c  o  m*/
     * Atomically adds the value to the atomic variable, capping the sum at Long.MAX_VALUE
     * and returning the original value.
     * @param <T> the type of the parent class of the field
     * @param updater the field updater
     * @param instance the instance of the field to update
     * @param n the value to add, n > 0, not validated
     * @return the original value before the add
     */
    public static <T> long getAndAddCap(AtomicLongFieldUpdater<T> updater,
            T instance, long n) {
        for (;;) {
            long r = updater.get(instance);
            if (r == Long.MAX_VALUE) {
                return Long.MAX_VALUE;
            }
            long u = addCap(r, n);
            if (updater.compareAndSet(instance, r, u)) {
                return r;
            }
        }
    }

    public static long addCap(long a, long b) {
        long u = a + b;
        if (u < 0) {
            return Long.MAX_VALUE;
        }
        return u;
    }
}

Related

  1. currentDate()
  2. generateId()
  3. generateId()
  4. generateRandom()
  5. get(T stat, AtomicIntegerFieldUpdater updater, boolean reset)
  6. getAndAddRequest(AtomicLong requested, long n)
  7. getAndAddRequest(AtomicLongFieldUpdater requested, T object, long n)
  8. getAtomicLongArraySameLengthAsList(List list)
  9. getBench(Map times, int amount)