Análisis del código fuente de Java nio AtomicIntegerArray

Tabla de contenido

Introducción

Campo inseguro, base, desplazamiento, matriz, método verificado ByteOffset, byteOffset, 2 constructores

Longitud de los métodos, get, getRaw, set, lazySet, getAndSet, 3 XXXcompareAndSetXXX

Método 5 getAndXXX, 5 XXXAndGet, toString


Introducción

package java.util.concurrent.atomic;
import java.util.function.IntUnaryOperator;
import java.util.function.IntBinaryOperator;
import sun.misc.Unsafe;

/**
 * 一个可以自动更新元素的int数组。
 * 看到java.util.concurrent.atomic包的描述原子变量属性的规范。
 * 
 * 相比其他原子类,原子数组类AtomicIntegerArray,它的成员不再是volatile的,而是final的。从设计上来讲,作为原子数组类的数组成员初始化后,确实也不应该被修改引用了。
 * 计算数组元素的地址偏移时,需要两个值,base和元素索引。
 * get/set函数不能像其他原子类一样,get直接return成员,set直接赋值成员。只能借助unsafe的getIntVolatile / putIntVolatile(array, offset)。
 * 其他的操作与AtomicInteger的区别是 getAndSetInt(this, valueOffset, newValue) 和 getAndSetInt(array, checkedByteOffset(i), newValue)
 * 
 * 
 * @since 1.5
 * @author Doug Lea
 */
public class AtomicIntegerArray implements java.io.Serializable 

Campo inseguro, base, desplazamiento, matriz, método verificado ByteOffset, byteOffset, 2 constructores

    private static final long serialVersionUID = 2862133569453604235L;

    private static final Unsafe unsafe = Unsafe.getUnsafe();
    // int数组内部的起始位置
    private static final int base = unsafe.arrayBaseOffset(int[].class);
    private static final int shift;
    private final int[] array;

    static {
    	// arrayIndexScale得到数组元素类型的大小,这里是int是4字节,所以返回4。scale为4。
        int scale = unsafe.arrayIndexScale(int[].class);
        // (scale & (scale - 1)) != 0这个判断,只有当scale为2的幂时,scale & (scale - 1)就会刚好等于0,然后判断为false,不会抛出异常。
        if ((scale & (scale - 1)) != 0)
            throw new Error("data type scale not a power of two");
        // scale和shift的关系是 scale = 2 ^ shift。
        // 运算过程是这样的:因为scale是int型,所以使用Integer.numberOfLeadingZeros()(见注释)
        // scale为4即0b100,int型总共32个bit,所以第一个1前面有29个0,numberOfLeadingZeros返回29。
        // 又因为使用的Integer.numberOfLeadingZeros(),所以前面那个数为32 -1。最终,31 - 29 = 2,即最终shift = 2。
        shift = 31 - Integer.numberOfLeadingZeros(scale);
    }

    private long checkedByteOffset(int i) {
        if (i < 0 || i >= array.length)
            throw new IndexOutOfBoundsException("index " + i);

        return byteOffset(i);
    }

    /** byteOffset函数,传入元素索引,返回这个数组元素的起始地址。
     * 
     *   既然是数组,所以要操作数组元素。
     *   而数组的内部存储方式有可能是先存size,再存各个元素,所以第一个元素的起始地址需要通过arrayBaseOffset确认。
     *   根据base地址,再加上 (元素个数-1) * 类型大小,就得到某个元素的起始地址。
     *   
     *   前面说到需要计算(元素个数-1) * 类型大小,现在看byteOffset函数的实现,你会发现 i << shift = i * 2 ^ shift = i * scale,当然前提是左移没有超过最高位。
     *   而i传入的都是索引(元素的第几个减1),所以((long) i << shift) + base刚好就是(元素个数-1) * 类型大小了。
     * @param i
     * @return
     */
    private static long byteOffset(int i) {
        return ((long) i << shift) + base;
    }

    /**
     * 创建一个给定长度的AtomicIntegerArray,所有元素初始化为0。
     *
     * @param length the length of the array
     */
    public AtomicIntegerArray(int length) {
        array = new int[length];
    }

    /**
     * 创建一个新的AtomicIntegerArray,其长度与给定数组相同,并复制其中的所有元素。
     *
     * @param array the array to copy elements from
     * @throws NullPointerException if array is null
     */
    public AtomicIntegerArray(int[] array) {
        // final字段保证了可见性
    	// 通过克隆一个传入数组。也算是新建数组了。
        this.array = array.clone();
    }

Longitud de los métodos, get, getRaw, set, lazySet, getAndSet, 3 XXXcompareAndSetXXX


    /**
     * 返回数组的长度。
     *
     * @return the length of the array
     */
    public final int length() {
        return array.length;
    }

    /**
     * 获取位置i的当前值。
     * 
     * 由于array成员不是volatile的,所以get/set时,都借助了unsafe,对array的对应偏移量,来达到volatile语义的get/set。
     *
     * @param i the index
     * @return the current value
     */
    public final int get(int i) {
        return getRaw(checkedByteOffset(i));
    }

    private int getRaw(long offset) {
        return unsafe.getIntVolatile(array, offset);
    }

    /**
     * 将位置i的元素设置为给定的值。
     *
     * @param i the index
     * @param newValue the new value
     */
    public final void set(int i, int newValue) {
        unsafe.putIntVolatile(array, checkedByteOffset(i), newValue);
    }

    /**
     * 最终将位置i的元素设置为给定值。
     * lazySet则不保证可见性。
     *
     * @param i the index
     * @param newValue the new value
     * @since 1.6
     */
    public final void lazySet(int i, int newValue) {
        unsafe.putOrderedInt(array, checkedByteOffset(i), newValue);
    }

    /**
     * 原子地将位置i的元素设置为给定值并返回旧值。
     * 
     * getAndSet直接设置新值,但getAndSetInt也是循环加CAS,因为需要正确返回设置成功时的旧值。
     * 最终使用unsafe.compareAndSwapInt,反正将array当成普通对象,直接从地址偏移来进行CAS操作。
     *
     * @param i the index
     * @param newValue the new value
     * @return the previous value
     */
    public final int getAndSet(int i, int newValue) {
        return unsafe.getAndSetInt(array, checkedByteOffset(i), newValue);
    }

    /**
     * 如果当前值==期望值,则原子地将位置i的元素设置为给定的更新值。
     *
     * @param i the index
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(int i, int expect, int update) {
        return compareAndSetRaw(checkedByteOffset(i), expect, update);
    }

    private boolean compareAndSetRaw(long offset, int expect, int update) {
        return unsafe.compareAndSwapInt(array, offset, expect, update);
    }

    /**
     * 如果当前值==期望值,则原子地将位置i的元素设置为给定的更新值。
     *
     * <p>可能会错误地失败,并且不提供排序保证,所以它很少是compareAndSet的合适选择。
     *
     * @param i the index
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful
     */
    public final boolean weakCompareAndSet(int i, int expect, int update) {
        return compareAndSet(i, expect, update);
    }

Método 5 getAndXXX, 5 XXXAndGet, toString


    /**
     * 将下标i处的元素原子地加1。
     *
     * @param i the index
     * @return the previous value
     */
    public final int getAndIncrement(int i) {
        return getAndAdd(i, 1);
    }

    /**
     * Atomically decrements by one the element at index {@code i}.
     *
     * @param i the index
     * @return the previous value
     */
    public final int getAndDecrement(int i) {
        return getAndAdd(i, -1);
    }

    /**
     * Atomically adds the given value to the element at index {@code i}.
     *
     * @param i the index
     * @param delta the value to add
     * @return the previous value
     */
    public final int getAndAdd(int i, int delta) {
        return unsafe.getAndAddInt(array, checkedByteOffset(i), delta);
    }

    /**
     * Atomically increments by one the element at index {@code i}.
     *
     * @param i the index
     * @return the updated value
     */
    public final int incrementAndGet(int i) {
        return getAndAdd(i, 1) + 1;
    }

    /**
     * Atomically decrements by one the element at index {@code i}.
     *
     * @param i the index
     * @return the updated value
     */
    public final int decrementAndGet(int i) {
        return getAndAdd(i, -1) - 1;
    }

    /**
     * Atomically adds the given value to the element at index {@code i}.
     *
     * @param i the index
     * @param delta the value to add
     * @return the updated value
     */
    public final int addAndGet(int i, int delta) {
        return getAndAdd(i, delta) + delta;
    }


    /**
     * 原子地用应用给定函数的结果更新索引i处的元素,返回前一个值。
     * 这个函数应该是没有副作用的,因为当尝试的更新由于线程间的争用而失败时,它可能会被重新应用。
     *
     * @param i the index
     * @param updateFunction a side-effect-free function
     * @return the previous value
     * @since 1.8
     */
    public final int getAndUpdate(int i, IntUnaryOperator updateFunction) {
        long offset = checkedByteOffset(i);
        int prev, next;
        do {
            prev = getRaw(offset);
            next = updateFunction.applyAsInt(prev);
        } while (!compareAndSetRaw(offset, prev, next));
        return prev;
    }

    /**
     * Atomically updates the element at index {@code i} with the results
     * of applying the given function, returning the updated value. The
     * function should be side-effect-free, since it may be re-applied
     * when attempted updates fail due to contention among threads.
     *
     * @param i the index
     * @param updateFunction a side-effect-free function
     * @return the updated value
     * @since 1.8
     */
    public final int updateAndGet(int i, IntUnaryOperator updateFunction) {
        long offset = checkedByteOffset(i);
        int prev, next;
        do {
            prev = getRaw(offset);
            next = updateFunction.applyAsInt(prev);
        } while (!compareAndSetRaw(offset, prev, next));
        return next;
    }

    /**
     * 原子地更新索引i处的元素,使用将给定函数应用到当前值和给定值的结果,返回前一个值。
     * 这个函数应该是没有副作用的,因为当由于线程间的争用而导致更新失败时,它可能会被重新应用。
     * 应用函数时,第一个参数是当前索引i处的值,第二个参数是给定的update。
     *
     * @param i the index
     * @param x the update value
     * @param accumulatorFunction a side-effect-free function of two arguments
     * @return the previous value
     * @since 1.8
     */
    public final int getAndAccumulate(int i, int x,
                                      IntBinaryOperator accumulatorFunction) {
        long offset = checkedByteOffset(i);
        int prev, next;
        do {
            prev = getRaw(offset);
            next = accumulatorFunction.applyAsInt(prev, x);
        } while (!compareAndSetRaw(offset, prev, next));
        return prev;
    }

    /**
     * Atomically updates the element at index {@code i} with the
     * results of applying the given function to the current and
     * given values, returning the updated value. The function should
     * be side-effect-free, since it may be re-applied when attempted
     * updates fail due to contention among threads.  The function is
     * applied with the current value at index {@code i} as its first
     * argument, and the given update as the second argument.
     *
     * @param i the index
     * @param x the update value
     * @param accumulatorFunction a side-effect-free function of two arguments
     * @return the updated value
     * @since 1.8
     */
    public final int accumulateAndGet(int i, int x,
                                      IntBinaryOperator accumulatorFunction) {
        long offset = checkedByteOffset(i);
        int prev, next;
        do {
            prev = getRaw(offset);
            next = accumulatorFunction.applyAsInt(prev, x);
        } while (!compareAndSetRaw(offset, prev, next));
        return next;
    }

    /**
     * 返回数组当前值的字符串表示形式。
     * @return the String representation of the current values of array
     */
    public String toString() {
        int iMax = array.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(getRaw(byteOffset(i)));
            if (i == iMax)
                return b.append(']').toString();
            b.append(',').append(' ');
        }
    }

 

Supongo que te gusta

Origin blog.csdn.net/xushiyu1996818/article/details/113941532
Recomendado
Clasificación