Example usage for java.util.concurrent.atomic AtomicLongFieldUpdater compareAndSet

List of usage examples for java.util.concurrent.atomic AtomicLongFieldUpdater compareAndSet

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicLongFieldUpdater compareAndSet.

Prototype

public abstract boolean compareAndSet(T obj, long expect, long update);

Source Link

Document

Atomically sets the field of the given object managed by this updater to the given updated value if the current value == the expected value.

Usage

From source file:Main.java

public static <T> long getAndAddRequest(AtomicLongFieldUpdater<T> requested, T object, long n) {
    long current;
    long next;/*from  w w  w. ja va  2  s  . c  o  m*/
    do {
        current = requested.get(object);
        next = current + n;
        if (next < 0) {
            next = Long.MAX_VALUE;
        }
    } while (!requested.compareAndSet(object, current, next));
    return current;
}

From source file:Main.java

/**
 * Adds {@code n} to {@code requested} field and returns the value prior to
 * addition once the addition is successful (uses CAS semantics). If
 * overflows then sets {@code requested} field to {@code Long.MAX_VALUE}.
 * /*from   w w w. j av a2 s. co m*/
 * @param <T> the type of the target object on which the field updater operates
 * 
 * @param requested
 *            atomic field updater for a request count
 * @param object
 *            contains the field updated by the updater
 * @param n
 *            the number of requests to add to the requested count
 * @return requested value just prior to successful addition
 * @deprecated Android has issues with reflection-based atomics
 */
@Deprecated
public static <T> long getAndAddRequest(AtomicLongFieldUpdater<T> requested, T object, long n) {
    // add n to field but check for overflow
    while (true) {
        long current = requested.get(object);
        long next = addCap(current, n);
        if (requested.compareAndSet(object, current, next)) {
            return current;
        }
    }
}

From source file:Main.java

static <T> long getAndAddRequest(AtomicLongFieldUpdater<T> paramAtomicLongFieldUpdater, T paramT,
        long paramLong) {
    long l1;//from   w  w  w  .j a va2  s .co  m
    long l2;
    do {
        l1 = paramAtomicLongFieldUpdater.get(paramT);
        l2 = l1 + paramLong;
        if (l2 < 0L)
            l2 = 9223372036854775807L;
    } while (!paramAtomicLongFieldUpdater.compareAndSet(paramT, l1, l2));
    return l1;
}