AtomicReferenceArray源码解析

AtomicReferenceArray源码解析

AtomicReferenceArray类介绍

java.util.concurrent.atomic.AtomicReferenceArray类提供了可以原子读取和写入的底层引用数组的操作,并且还包含高级原子操作。 AtomicReferenceArray支持对底层引用数组变量的原子操作。 它具有获取和设置方法,如在变量上的读取和写入。 也就是说,一个集合与同一变量上的任何后续获取相关联。 原子compareAndSet方法也具有这些内存一致性功能。

类图

AtomicReferenceArray类图

主要属性

1
2
3
4
5
private static final Unsafe unsafe;
private static final int base;
private static final int shift;
private static final long arrayFieldOffset;
private final Object[] array; // must have exact type Object[]

unsafe:Unsafe,JDK提供的实现CAS算法的类

base:数组中第一个元素的内存地址

shift:左移偏移量。基于对象的数组,shift是根据不同对象来决定不同值的用来计算,数组中的元素在整个AtomicReferenceArray对象中的偏移量。数组中第i个元素的地址就是 i << shift + base.

arrayFieldOffset: array 相对于对象的偏移量

上述三个字段会在静态代码块中完成初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
static {
try {
unsafe = Unsafe.getUnsafe();
arrayFieldOffset = unsafe.objectFieldOffset
(AtomicReferenceArray.class.getDeclaredField("array"));
base = unsafe.arrayBaseOffset(Object[].class);
int scale = unsafe.arrayIndexScale(Object[].class);
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
shift = 31 - Integer.numberOfLeadingZeros(scale);
} catch (Exception e) {
throw new Error(e);
}
}

toString():存放元素的数组

主要方法

checkedByteOffset(int)

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

return byteOffset(i);
}

检验索引是否越界,并返回对应位置的偏移量

byteOffset(int)

1
2
3
private static long byteOffset(int i) {
return ((long) i << shift) + base;
}

返回对应索引的偏移量

AtomicReferenceArray(int)

1
2
3
4
5
6
7
8
9
/**
* Creates a new AtomicReferenceArray of the given length, with all
* elements initially null.
*
* @param length the length of the array
*/
public AtomicReferenceArray(int length) {
array = new Object[length];
}

创建指定长度的原子引用数组

AtomicReferenceArray(E[])

1
2
3
4
5
6
7
8
9
10
11
/**
* Creates a new AtomicReferenceArray with the same length as, and
* all elements copied from, the given array.
*
* @param array the array to copy elements from
* @throws NullPointerException if array is null
*/
public AtomicReferenceArray(E[] array) {
// Visibility guaranteed by final field guarantees
this.array = Arrays.copyOf(array, array.length, Object[].class);
}

根据给定的数组,创建相同长度的原子引用数组。

length()

1
2
3
4
5
6
7
8
/**
* Returns the length of the array.
*
* @return the length of the array
*/
public final int length() {
return array.length;
}

返回当前数组的长度

get(int)

1
2
3
4
5
6
7
8
9
/**
* Gets the current value at position {@code i}.
*
* @param i the index
* @return the current value
*/
public final E get(int i) {
return getRaw(checkedByteOffset(i));
}

返回指定索引上的值

getRaw(long)

1
2
3
4
@SuppressWarnings("unchecked")
private E getRaw(long offset) {
return (E) unsafe.getObjectVolatile(array, offset);
}

调用unsafe,获取指定位移上的值

set(int, E)

1
2
3
4
5
6
7
8
9
/**
* Sets the element at position {@code i} to the given value.
*
* @param i the index
* @param newValue the new value
*/
public final void set(int i, E newValue) {
unsafe.putObjectVolatile(array, checkedByteOffset(i), newValue);
}

将指定位置上的值设置为newValue

lazySet(int,E)

1
2
3
4
5
6
7
8
9
10
/**
* Eventually sets the element at position {@code i} to the given value.
*
* @param i the index
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(int i, E newValue) {
unsafe.putOrderedObject(array, checkedByteOffset(i), newValue);
}

调用unsafe的方法直接将位置i上的值设置为给定的新值。但是这个方法有别于上面的set方法,它在一段时间内是有可能让其他线程查到原来的旧值,而不是立马查到新值。因此,它可以算是一个“最终一致性”的方法

getAndSet(int,E)

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Atomically sets the element at position {@code i} to the given
* value and returns the old value.
*
* @param i the index
* @param newValue the new value
* @return the previous value
*/
@SuppressWarnings("unchecked")
public final E getAndSet(int i, E newValue) {
return (E)unsafe.getAndSetObject(array, checkedByteOffset(i), newValue);
}

获取当前值,返回,并将当前值设置为newValue

compareAndSet(int,E,E)

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Atomically sets the element at position {@code i} to the given
* updated value if the current value {@code ==} the expected value.
*
* @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, E expect, E update) {
return compareAndSetRaw(checkedByteOffset(i), expect, update);
}

如果位置i上的值等同于except,那就将该值更新为update,并返回true,否则返回false。

compareAndSetRaw(long,E,E)

1
2
3
private boolean compareAndSetRaw(long offset, E expect, E update) {
return unsafe.compareAndSwapObject(array, offset, expect, update);
}

如果指定偏移量处的值等同于except,那就将该值更新为update,并返回true,否则返回false。

weakCompareAndSet(int, E,E)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Atomically sets the element at position {@code i} to the given
* updated value if the current value {@code ==} the expected value.
*
* <p><a href="package-summary.html#weakCompareAndSet">May fail
* spuriously and does not provide ordering guarantees</a>, so is
* only rarely an appropriate alternative to {@code 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, E expect, E update) {
return compareAndSet(i, expect, update);
}

这个方法的本意是,调用weakCompareAndSet方法时不能保证指令重排的发生,因此,这个方法有时候会毫无理由地失败。

但是从实现上来看,这个方法还是和compareAndSet一模一样的。不过建议在使用的时候,谨慎对待,保不定什么时候,方法实现就修改了。

getAndUpdate(int,UnaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Atomically updates the element at index {@code i} with the results
* of applying the given function, returning the previous 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 previous value
* @since 1.8
*/
public final E getAndUpdate(int i, UnaryOperator<E> updateFunction) {
long offset = checkedByteOffset(i);
E prev, next;
do {
prev = getRaw(offset);
next = updateFunction.apply(prev);
} while (!compareAndSetRaw(offset, prev, next));
return prev;
}

获取位置i上的值,并将该值应用于单元函数updateFunction,并将其结果更新于当前值。需要注意的是,此处使用的是一个循环,如果一直更新不成功的话,线程会一直自旋在此处。

updateAndGet(int, UnaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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 E updateAndGet(int i, UnaryOperator<E> updateFunction) {
long offset = checkedByteOffset(i);
E prev, next;
do {
prev = getRaw(offset);
next = updateFunction.apply(prev);
} while (!compareAndSetRaw(offset, prev, next));
return next;
}

将当前值应用单元函数,并将获得的值更新当前值,返回。需要注意的是,此处使用的是一个循环,如果一直更新不成功的话,线程会一直自旋在此处。

getAndAccumulate(int,E,BinaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Atomically updates the element at index {@code i} with the
* results of applying the given function to the current and
* given values, returning the previous 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 previous value
* @since 1.8
*/
public final E getAndAccumulate(int i, E x,
BinaryOperator<E> accumulatorFunction) {
long offset = checkedByteOffset(i);
E prev, next;
do {
prev = getRaw(offset);
next = accumulatorFunction.apply(prev, x);
} while (!compareAndSetRaw(offset, prev, next));
return prev;
}

返回当前值。并将x和当前值应用于双元函数,将其结果更新值当前值上。需要注意的是,此处使用的是一个循环,如果一直更新不成功的话,线程会一直自旋在此处。

accumulateAndGet(int,E,BinaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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 E accumulateAndGet(int i, E x,
BinaryOperator<E> accumulatorFunction) {
long offset = checkedByteOffset(i);
E prev, next;
do {
prev = getRaw(offset);
next = accumulatorFunction.apply(prev, x);
} while (!compareAndSetRaw(offset, prev, next));
return next;
}

将x和当前值应用于双元函数,并将其结果更新至当前值,返回。需要注意的是,此处使用的是一个循环,如果一直更新不成功的话,线程会一直自旋在此处。

toString()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Returns the String representation of the current values of array.
* @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(' ');
}
}

返回当前数组的字符串形式

readObject(ObjectInputStream)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException,
java.io.InvalidObjectException {
// Note: This must be changed if any additional fields are defined
Object a = s.readFields().get("array", null);
if (a == null || !a.getClass().isArray())
throw new java.io.InvalidObjectException("Not array type");
if (a.getClass() != Object[].class)
a = Arrays.copyOf((Object[])a, Array.getLength(a), Object[].class);
unsafe.putObjectVolatile(this, arrayFieldOffset, a);
}

从输入流中读取数据并构造数组。