Java AtomicLong getAndAddRequest(AtomicLong requested, long n)

Here you can find the source of getAndAddRequest(AtomicLong requested, long n)

Description

Adds n (not validated) to requested and returns the value prior to addition once the addition is successful (uses CAS semantics).

License

Apache License

Parameter

Parameter Description
requested atomic long that should be updated
n the number of requests to add to the requested count, positive (not validated)

Return

requested value just prior to successful addition

Declaration

public static long getAndAddRequest(AtomicLong requested, long n) 

Method Source Code

//package com.java2s;
/**// w ww  . j a  va2s  . com
 * Copyright 2015 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import java.util.concurrent.atomic.*;

public class Main {
    /**
     * Adds {@code n} (not validated) to {@code requested} 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}.
     *
     * @param requested
     *            atomic long that should be updated
     * @param n
     *            the number of requests to add to the requested count, positive (not validated)
     * @return requested value just prior to successful addition
     */
    public static long getAndAddRequest(AtomicLong requested, long n) {
        // add n to field but check for overflow
        while (true) {
            long current = requested.get();
            long next = addCap(current, n);
            if (requested.compareAndSet(current, next)) {
                return current;
            }
        }
    }

    /**
     * Adds two positive longs and caps the result at Long.MAX_VALUE.
     * @param a the first value
     * @param b the second value
     * @return the capped sum of a and b
     */
    public static long addCap(long a, long b) {
        long u = a + b;
        if (u < 0L) {
            u = Long.MAX_VALUE;
        }
        return u;
    }
}

Related

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