AtomicLong源码解析

AtomicLong源码解析

AtomicLong是在JDK的java.util.concurrent.atomic包中提供的,线程安全的Long操作类。之所以说它是线程安全的,是相对于long类型的数据来说的。

比如下面这个例子:

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
26
27
28
public class UseLongUnsafe implements Runnable {
private static long value = 0;

@Override
public void run() {
for (int i = 0;i < 1000;i++) {
value++;
}
}

public static void main(String[] args) {
UseLongUnsafe unsafe = new UseLongUnsafe();

for (int i = 0;i < 10;i++) {
Thread t = new Thread(unsafe);
t.start();
}

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final value is " + value);
}

}

上述代码做的事情:

  1. 声明一个静态的long值value
  2. 实现Runnable接口,并实现其run方法
  3. 在run方法中对value自增1000次
  4. 开启10个线程,每个线程对value自增1000次
  5. 观察结果。

运行上述代码,可以发现每次跑完的结果都不一样:

运行结果1

运行结果2

运行结果3

这是因为int类型在自增的时候(i++或者++i),不是一个原子操作完成的。它大略可以分为三步

  1. 从原来的地址中取出值
  2. 对值加1
  3. 放回原来的地址

这三步中,任何一步在执行的时候,线程被切换走,都会导致最后结果的不一致。

因此,JDK就提供了一个采用CAS思想实现的原子类AtomicLong。

AtomicLong类介绍

类图

AtomicLong

AtomicLong继承了抽象类Number,并实现了其longValue,doubleValue等方法。

主要属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// setup to use Unsafe.compareAndSwapLong for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;

/**
* Records whether the underlying JVM supports lockless
* compareAndSwap for longs. While the Unsafe.compareAndSwapLong
* method works in either case, some constructions should be
* handled at Java level to avoid locking user-visible locks.
*/
static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8();

/**
* Returns whether underlying JVM supports lockless CompareAndSet
* for longs. Called only once and cached in VM_SUPPORTS_LONG_CAS.
*/
private static native boolean VMSupportsCS8();

private volatile long value;

unsafe:sun提供的实现CAS的主要工具类

valueOffset:当前值value在整个AtomicLong对象中的内存偏移量。这个值在下面的代码块中完成初始化

1
2
3
4
5
6
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicLong.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}

VM_SUPPORTS_LONG_CAS:记录底层JVM是否支持longs的无锁compareAndSwap。
虽然Unsafe.compareAndSwapLong方法在任何一种情况下都可以工作,
但是应该在Java级别处理一些构造以避免锁定用户可见的锁。

value:保存long的值

**VMSupportsCS8()**:返回底层JVM是否支持longs的无锁CompareAndSet。 仅调用一次并缓存在VM_SUPPORTS_LONG_CAS中。

主要方法

AtomicLong(long)

1
2
3
4
5
6
7
8
/**
* Creates a new AtomicLong with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicLong(long initialValue) {
value = initialValue;
}

指定初始值生成一个AtomicLong对象

AtomicLong()

1
2
3
4
5
/**
* Creates a new AtomicLong with initial value {@code 0}.
*/
public AtomicLong() {
}

生成一个默认的AtomicLong对象。值默认为0

get()

1
2
3
4
5
6
7
8
/**
* Gets the current value.
*
* @return the current value
*/
public final long get() {
return value;
}

获取当前值

set(long)

1
2
3
4
5
6
7
8
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(long newValue) {
value = newValue;
}

将value值设置为当前值newValue

lazySet(long)

1
2
3
4
5
6
7
8
9
/**
* Eventually sets to the given value.
*
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(long newValue) {
unsafe.putOrderedLong(this, valueOffset, newValue);
}

“慢慢”地将value的值设置为newValue。是一个最终一致性的方法。意味着,在极短的一段时间内,其他线程还是可能读取到value而不是newValue。

getAndSet(long)

1
2
3
4
5
6
7
8
9
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final long getAndSet(long newValue) {
return unsafe.getAndSetLong(this, valueOffset, newValue);
}

获取当前value的值,并将value的值设置为newValue

public final boolean compareAndSet(long, long)

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @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(long expect, long update) {
return unsafe.compareAndSwapLong(this, valueOffset, expect, update);
}

如果当前value的值为expect,那么将当前值设置为update。否则返回false。如果设置成功返回true,否则返回false。

public final boolean weakCompareAndSet(long, long)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Atomically sets the value 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 expect the expected value
* @param update the new value
* @return {@code true} if successful
*/
public final boolean weakCompareAndSet(long expect, long update) {
return unsafe.compareAndSwapLong(this, valueOffset, expect, update);
}

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

但是从实现上来看,该方法是和compareAndSet的实现是一致的。

getAndIncrement()

1
2
3
4
5
6
7
8
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final long getAndIncrement() {
return unsafe.getAndAddLong(this, valueOffset, 1L);
}

获取当前的值并对当前的值加1

getAndDecrement()

1
2
3
4
5
6
7
8
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final long getAndDecrement() {
return unsafe.getAndAddLong(this, valueOffset, -1L);
}

获取当前的值并对当前的值减1

getAndAdd(long)

1
2
3
4
5
6
7
8
9
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final long getAndAdd(long delta) {
return unsafe.getAndAddLong(this, valueOffset, delta);
}

获取当前value的值并对该值加上delta。

incrementAndGet()

1
2
3
4
5
6
7
8
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final long incrementAndGet() {
return unsafe.getAndAddLong(this, valueOffset, 1L) + 1L;
}

对当前值加1,并返回更新后的值

decrementAndGet()

1
2
3
4
5
6
7
8
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final long decrementAndGet() {
return unsafe.getAndAddLong(this, valueOffset, -1L) - 1L;
}

对当前值减1,并返回更新后的值

addAndGet(long)

1
2
3
4
5
6
7
8
9
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final long addAndGet(long delta) {
return unsafe.getAndAddLong(this, valueOffset, delta) + delta;
}

对当前值加上delta,并返回更新后的值

getAndUpdate(LongUnaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Atomically updates the current value 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 updateFunction a side-effect-free function
* @return the previous value
* @since 1.8
*/
public final long getAndUpdate(LongUnaryOperator updateFunction) {
long prev, next;
do {
prev = get();
next = updateFunction.applyAsLong(prev);
} while (!compareAndSet(prev, next));
return prev;
}

获取当前值,并对当前值应用Long型单元函数,并将获得的结果设置为最新的value值。

updateAndGet(LongUnaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Atomically updates the current value 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 updateFunction a side-effect-free function
* @return the updated value
* @since 1.8
*/
public final long updateAndGet(LongUnaryOperator updateFunction) {
long prev, next;
do {
prev = get();
next = updateFunction.applyAsLong(prev);
} while (!compareAndSet(prev, next));
return next;
}

对当前值应用Long型单元函数,并将获得的结果设置为最新的value值,返回最新的value值。

getAndAccumulate(long,LongBinaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Atomically updates the current value 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 as its first argument,
* and the given update as the second argument.
*
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the previous value
* @since 1.8
*/
public final long getAndAccumulate(long x,
LongBinaryOperator accumulatorFunction) {
long prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsLong(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}

获取当前值,并对x和当前值value应用二元函数,并将得到的结果设置为最新的value值。

accumulateAndGet(long,LongBinaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Atomically updates the current value 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 as its first argument,
* and the given update as the second argument.
*
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the updated value
* @since 1.8
*/
public final long accumulateAndGet(long x,
LongBinaryOperator accumulatorFunction) {
long prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsLong(prev, x);
} while (!compareAndSet(prev, next));
return next;
}

对value和x应用二元函数,并将得到的结果设置为最新的value,并返回

toString()

1
2
3
4
5
6
7
/**
* Returns the String representation of the current value.
* @return the String representation of the current value
*/
public String toString() {
return Long.toString(get());
}

返回long型value的字符串类型

intValue()

1
2
3
4
5
6
7
8
/**
* Returns the value of this {@code AtomicLong} as an {@code int}
* after a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/
public int intValue() {
return (int)get();
}

将当前的value转为int返回。需要注意类型变窄

longValue()

1
2
3
4
5
6
/**
* Returns the value of this {@code AtomicLong} as a {@code long}.
*/
public long longValue() {
return get();
}

返回当前值

floatValue()

1
2
3
4
5
6
7
8
/**
* Returns the value of this {@code AtomicLong} as a {@code float}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public float floatValue() {
return (float)get();
}

将当前值转为float返回

doubleValue()

1
2
3
4
5
6
7
8
/**
* Returns the value of this {@code AtomicLong} as a {@code double}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public double doubleValue() {
return (double)get();
}

将当前值转为double返回

应用

下面将使用AtomicLong类改写上面多线程环境下不安全的代码。

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
26
27
28
public class UseAtomicLong implements Runnable {
public static AtomicLong value = new AtomicLong();

@Override
public void run() {
for (int i = 0;i < 1000;i++) {
value.incrementAndGet();
}
}

public static void main(String[] args) {
UseAtomicLong unsafe = new UseAtomicLong();

for (int i = 0;i < 10;i++) {
Thread t = new Thread(unsafe);
t.start();
}

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final value is " + value.get());
}
}

改写之后,无论再怎么运行,都不会出现值不是10000的情况了。

0%