前言
最近在看JDK源码,发现好多地方都用到了AtomicInteger原子类,所以打算将AtmoicInteger的源码过一遍。
本文将分为两部分,一部分是简单介绍AtmoicInteger的用法,第二部分是AtomicInteger的源码,我在源码中做了比较详细的注释。
简单使用AtomicInteger
下面介绍AtomicInteger的一部分API的使用示例,未列出的api可以在后面的源码中看到用法
package cn.ganlixin;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 描述:
* 测试使用AtomicInteger
*
* @author ganlixin
* @create 2020-06-11
*/
public class TestAtomicInteger {
@Test
public void test() {
AtomicInteger atomicInteger = new AtomicInteger();
// AtomicInteger ai = new AtomicInteger(10); 赋初始值为10
System.out.println(atomicInteger.get()); // 0
// 修改值
atomicInteger.set(100);
// 获取当前值,然后设置新值
System.out.println(atomicInteger.getAndSet(99));// 100
System.out.println(atomicInteger.get()); // 99
// 获取当前值,然后对其进行加20
System.out.println(atomicInteger.getAndAdd(20)); // 99
System.out.println(atomicInteger.get()); // 119
// lazySet和set功能一样,但是不能保证立即修改值(最终会修改)
atomicInteger.lazySet(100);
System.out.println(atomicInteger.get()); // 100
// 新增1并返回新值,原子操作
System.out.println(atomicInteger.incrementAndGet()); // 101
// CAS原子操作更改value
System.out.println(atomicInteger.compareAndSet(102, 1000)); // false
System.out.println(atomicInteger.compareAndSet(101, 1000)); // true
}
}
AtomicInteger源码
源码如下,AtomicInteger的源码还是比较好理解的,基本没有难点,其中涉及到Unsafe类的使用,可以美团技术博客(Java魔法类-Unsafe应用解析)。
package java.util.concurrent.atomic;
import sun.misc.Unsafe;
import java.util.function.IntBinaryOperator;
import java.util.function.IntUnaryOperator;
/**
* 原子类
*/
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// Unsafe可以执行低级别、不安全操作的方法,比如直接访问系统内存资源、自主管理内存资源等
// 使用Unsafe,可以实现内存操作、CAS、内存屏障...在AtomicInteger中,主要用来进行CAS操作
private static final Unsafe unsafe = Unsafe.getUnsafe();
// value就是AtomicInteger保存的值,因为加了volatile关键字,所以在并发操作时,多线程能感知数据发生变化
private volatile int value;
// 该字段用来保存内存偏移地址,会在下面的静态代码块初始化
private static final long valueOffset;
static {
try {
// valueOffset为字段value的内存偏移地址(相对于atomicInteger对象基地址的偏移)
valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) {
throw new Error(ex);
}
}
/**
* 创建AtomicInteger对象,并设置初始值
*
* @param initialValue 初始值
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* 创建AtomicInteger对象,初始值为0
*/
public AtomicInteger() {
}
/**
* 获取value.
*
* @return 当前的value
*/
public final int get() {
return value;
}
/**
* 立即修改或者设置value
* set操作能够保证可见性,避免指令重排
*
* @param newValue 设置的新值
*/
public final void set(int newValue) {
value = newValue;
}
/**
* 不会立即修改或者设置值(但是最终会)
* lazySet不能保证可见性,可能会发生指令重排,但是性能比set高
*
* @param newValue 要设置的值
* @since 1.6
*/
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
/**
* 设置新值,并且返回旧值(原子操作)
*
* @param newValue 新值
* @return 旧值
*/
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
/**
* 原子操作,CAS,当value和expect相等时,才将value修改为update
*
* @param expect 期望value的值
* @param update 要修改的值
* @return true:value和expect相等,且完成修改;false:value和expect不相等
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* 和compareAndSet相同功能,都是使用CAS原子操作,但是无法保证多个线程CAS的有序性
*
* @param expect 期望的value值
* @param update 更改后的值
* @return 操作是否成功
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* 将value加1,然后返回旧值,原子操作
*
* @return 旧值
*/
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
/**
* 将value减1,然后返回旧值,原子操作
*
* @return 旧值
*/
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, valueOffset, -1);
}
/**
* 对value增加指定值,然后返回旧值,原子操作
*
* @param delta 要加的值
* @return 旧值
*/
public final int getAndAdd(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}
/**
* 将value加1,并返回新值,原子操作
*
* @return value加1后的值
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
/**
* 将value减1,并返回新值,原子操作
*
* @return value减1后的新值
*/
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
/**
* 对value增加值,然后返回新值,原子操作
*
* @param delta 新增的值
* @return value新增后的值
*/
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}
/**
* 传入Function,对value进行操作(同样使用CAS保证原子性),会一直重试直到成功才中断,然后返回旧值
*
* @param updateFunction a side-effect-free function
* @return 旧值
* @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;
}
/**
* 传入Function,对value进行操作(同样使用CAS保证原子性),会一直重试直到成功才中断,然后返回新值
*
* @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);
// 一直重试,直到CAS操作成功
} while (!compareAndSet(prev, next));
return next;
}
/**
* 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;
}
/**
* 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;
}
public String toString() {
return Integer.toString(get());
}
public int intValue() {
return get();
}
public long longValue() {
return (long) get();
}
public float floatValue() {
return (float) get();
}
public double doubleValue() {
return (double) get();
}
}