集册 Java实例教程 原子性地将实例中的数组替换为一个新数组,该数组也包含新值,如果实例包含终端值,则返回false。

原子性地将实例中的数组替换为一个新数组,该数组也包含新值,如果实例包含终端值,则返回false。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

430
原子性地将实例中的数组替换为一个新数组,该数组也包含新值,如果实例包含终端值,则返回false。

/**

 * 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.

 */
 /**
 来 自 NowJava.com - 时代Java
 **/

//package com.nowjava;

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);
            /*
            来 自*
             N  o w  J a v a . c o m
            */

            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 (;;) {

     
展开阅读全文