Atomically replaces the array in instance with a new array that contains the new Value as well or returns false if the instance holds the terminal Value. - Java Collection Framework

Java examples for Collection Framework:Array Contain

Description

Atomically replaces the array in instance with a new array that contains the new Value as well or returns false if the instance holds the terminal Value.

Demo Code

/**// w w  w  .  j  a v a  2 s. com
 * Copyright 2015 David Karnok and 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.
 */
//package com.java2s;
import java.util.concurrent.atomic.*;
import java.util.function.*;

public class Main {
    /**
     * Atomically replaces the array in instance with a new array that contains the newValue as well
     * or returns false if the instance holds the terminalValue.
     * @param updater
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param arraySupplier
     * @return
     */
    public static <T, U> boolean add(
            AtomicReferenceFieldUpdater<T, U[]> updater, T instance,
            U newValue, U[] terminalValue, IntFunction<U[]> arraySupplier) {
        for (;;) {
            U[] a = updater.get(instance);
            if (a == terminalValue) {
                return false;
            }
            int n = a.length;
            U[] b = arraySupplier.apply(n + 1);
            System.arraycopy(a, 0, b, 0, n);
            b[n] = newValue;
            if (updater.compareAndSet(instance, a, b)) {
                return true;
            }
        }
    }

    /**
     * Atomically replaces the array in instance with a new array that contains the newValue as well
     * or returns false if the instance holds the terminalValue.
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param arraySupplier
     * @return
     */
    public static <U> boolean add(AtomicReference<U[]> instance,
            U newValue, U[] terminalValue, IntFunction<U[]> arraySupplier) {
        for (;;) {
            U[] a = instance.get();
            if (a == terminalValue) {
                return false;
            }
            int n = a.length;
            U[] b = arraySupplier.apply(n + 1);
            System.arraycopy(a, 0, b, 0, n);
            b[n] = newValue;
            if (instance.compareAndSet(a, b)) {
                return true;
            }
        }
    }
}

Related Tutorials