AtomicInteger源码解析

AtomicInteger源码解析

AtomicInteger类介绍

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

比如下面这个例子:

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
29
30
public class UseIntUnsafe implements Runnable {
private static int value = 0;

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

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

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

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

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

}

上述代码做的事情:

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

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

运行结果1

运行结果2

运行结果3

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

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

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

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

类图

AtomicInteger的类图

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

主要属性

1
2
3
4
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
private volatile int value;

unsafe:是sun封装出来,主要实现CAS算法的实现类。Atomic*的类都是借助这个Unsafe类实现的

valueOffset:当前值value在整个类对象内存地址中的偏移值。这个值在一个静态的代码块中完成初始化

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

value:当前值

主要方法

AtomicInteger()

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

无参构造函数,value取默认值0

AtomicInteger(int)

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

有参构造函数,将value的值初始化为指定的initialValue

get()

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

获取当前值

set(int)

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

因为value是volatile修饰的,可以直接设值

lazySet(int)

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(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}

lazySet方法是由依赖于硬件的系统指令(如x86的xchg)实现的。使用lazySet的话,其他线程在之后的一小段时间里还是可以读到旧的值。lazySet方法相比于set方法可能性能好一点。

getAndSet(int)

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 int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}

设置新值,并返回当前值

compareAndSet(int, int)

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(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

当当前值等于expect的时候,将其设置为新值update。设置成功返回true,否则flase

weakCompareAndSet(int, int)

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(int expect, int update) {
return unsafe.compareAndSwapInt(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 int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}

将当前值自增1,并返回自增前的值

getAndDecrement()

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

将当前值自减1,并返回自增前的值

getAndAdd(int)

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 int getAndAdd(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}

将value加上指定的值,并返回未加之前的值

incrementAndGet()

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

将当前值加1,并返回最新值

decrementAndGet()

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

将当前值减1,并返回最新值

addAndGet(int)

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 int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}

将当前值加上指定的delta,并返回最新的值

getAndUpdate(IntUnaryOperator)

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 int getAndUpdate(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return prev;
}

用传入的单元函数对象计算并更新当前值,并返回更新之前的当前值

要求单元函数对象调用支持幂等,因为存在设值失败的场景。

updateAndGet(IntUnaryOperator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 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 int updateAndGet(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return next;
}

用传入的函数对象计算并更新当前值,并返回更新之后的当前值

要求单元函数对象调用支持幂等,因为存在设值失败的场景。

getAndAccumulate(int , IntBinaryOperator)

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 int getAndAccumulate(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}

value由当前值和传入的x和双元运算函数得到,并更新,返回更新前的value

要求双元运算函数具有幂等性,因为存在设值失败的场景

accumulateAndGet(int, IntBinaryOperator)

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 int accumulateAndGet(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(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 Integer.toString(get());
}

返回当前value值的字符串形式

intValue()

1
2
3
4
5
6
/**
* Returns the value of this {@code AtomicInteger} as an {@code int}.
*/
public int intValue() {
return get();
}

返回当前value值

longValue()

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

将当前值强转为long型,返回

floatValue()

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

将当前值强转为double返回

使用

了解了AtomicInteger的主要方法之后,我们再试着使用AtomicInteger改写上面的线程不安全的代码。

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 UseAtomicInteger implements Runnable {
private static AtomicInteger value = new AtomicInteger(0);

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

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

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

0%