# 一、Atomic 原子类简介
Atomic
原子:指一个操作是不可中断的,即使是在多个线程一起执行的时候,一个操作一旦开始,就不会被其他线程干扰。所谓原子类说简单点就是具有原子/原子操作特征的类。并发包java.util.concurrent
的原子类都存放在java.util.concurrent.atomic
下,如下图所示:

根据操作的数据类型,可以将JUC
包中的原子类分为4类:
# 二、基本类型
使用原子的方式更新基本类型。
■ AtomicInteger
:整型原子类
■ AtomicLong
:长整型原子类
■ AtomicBoolean
:布尔型原子类
上面三个类提供的方法几乎相同,所以我们这里以AtomicInteger
为例子来介绍。
public final int get() // 获取当前值
public final int getAndSet(int newValue) // 获取当前值,并设置新的值
public final boolean compareAndSet(int expect, int update) // 如果输入的数值等于预期值,则以原子方式将该值设置为输入值
public final int getAndIncrement() // 获取当前的值,并自增
public final int getAndDecrement() // 获取当前的值,并自减
public final int getAndAdd(int delta) // 获取当前的值,并加上预期的值
2
3
4
5
6
AtomicInteger
常见方法使用
public class AtomicIntegerTest {
public static void main(String[] args) {
int temvalue = 0;
AtomicInteger i = new AtomicInteger(0);
temvalue = i.getAndSet(3);
System.out.println("temvalue:" + temvalue + "; i:" + i); //temvalue:0;i:3
temvalue = i.getAndIncrement();
System.out.println("temvalue:" + temvalue + "; i:" + i); //temvalue:3;4
temvalue = i.getAndAdd(5);
System.out.println("temvalue:" + temvalue + "; i:" + i); //temvalue:4;9
}
}
2
3
4
5
6
7
8
9
10
11
12
AtomicInteger
线程安全原理简单分析: AtomicInteger
类的部分源码:
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
2
3
4
5
6
7
8
9
10
11
12
13
14
AtomicInteger
类主要利用CAS (compare and swap)
+volatile
和native
方法来保证原子操作,从而避免synchronized
的高开销,执行效率大为提升。
WARNING
被volatile
修饰的变量被修改时,会将修改后的变量直接写入主存中,并且将其他线程中该变量的缓存置为无效,从而让其它线程对该变量的引用直接从主存中获取数据,这样就保证了变量的可见性。
但是volatile
修饰的变量在自增时由于该操作分为读写两个步骤,所以当一个线程的读操作被阻塞时,另一个线程同时也进行了自增操作,此时由于第一个线程的写操作没有进行所以主存中仍旧是之前的原数据,所以当两个线程自增完成后,该变量可能只加了1。因而volatile
是无法保证对变量的任何操作都是原子性的。
CAS
的原理是拿期望的值和原本的一个值作比较,如果相同则更新成新的值。UnSafe
类的objectFieldOffset()
方法是一个本地方法,这个方法是用来拿到“原来的值”的内存地址。另外value
是一个volatile
变量,在内存中可见,因此JVM
可以保证任何时刻任何线程总能拿到该变量的最新值。
# 三、数组类型
使用原子的方式更新数组里的某个元素
■ AtomicIntegerArray
:整型数组原子类
■ AtomicLongArray
:长整型数组原子类
■ AtomicReferenceArray
:引用类型数组原子类
上面三个类提供的方法几乎相同,所以我们这里以AtomicIntegerArray
为例子来介绍。
AtomicIntegerArray
类常用方法
public final int get(int i) // 获取 index =i 位置元素的值
public final int getAndSet(int i, int newValue) // 返回 index=i 位置的当前值,并设置新的值:newValue
public final boolean compareAndSet(int i, int expect, int update) // 如果输入的数值等于预期值,则以原子方式将 index = i 位置元素值设置为输入值
public final int getAndIncrement(int i) // 获取 index =i 位置元素的值,并自增
public final int getAndDecrement(int i) // 获取 index =i 位置元素的值,并自减
public final int getAndAdd(int i, int delta) // 获取 index =i 位置元素的值,并加上预期的值
public final void lazySet(int i, int newValue) // 最终将 index = i位置的元素设置为 newVlaue,使用 lazySet 设置之后可能导致其它线程在之后的一段时间内还可以读到旧的值。
2
3
4
5
6
7
AtomicIntegerArray
常见方法使用
public class AtomicIntegerArrayTest {
public static void main(String[] args) {
int temvalue = 0;
int[] nums = {1,2,3,4,5,6};
AtomicIntegerArray i = new AtomicIntegerArray(nums);
for (int j = 0; j < nums.length; j++) {
System.out.println(i.get(j));
}
temvalue = i.getAndSet(0,2);
System.out.println("temvalue:" + temvalue + "; i:" + i); //temvalue:1; i:[2, 2, 3, 4, 5, 6]
temvalue = i.getAndIncrement(0);
System.out.println("temvalue:" + temvalue + "; i:" + i); //temvalue:2; i:[3, 2, 3, 4, 5, 6]
temvalue = i.getAndAdd(0,5);
System.out.println("temvalue:" + temvalue + "; i:" + i); //temvalue:3; i:[8, 2, 3, 4, 5, 6]
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 四、引用类型
基本类型原子类只能更新一个变量,如果需要原子更新多个变量,需要使用引用类型原子类。
■ AtomicReference
: 引用类型原子类
■ AtomicMarkableReference
:原子更新带有标记的引用类型。该类将boolean
标记与引用关联起来,不能解决ABA
问题。
■ AtomicStampedReference
:原子更新带有版本号的引用类型。该类将整数值与引用关联起来, 可用于解决原子的更新数据和数据的版本号,可以解决使用CAS
进行原子更新时可能出现的ABA
问题。
上面三个类提供的方法几乎相同,所以我们这里以AtomicReference
为例子来介绍。
@Test
public void AtomicReferenceTest() {
AtomicReference<Person> personAtomicReference = new AtomicReference<>();
Person person = new Person("zzx", 20);
personAtomicReference.set(person);
Person updatePerson = new Person("fanl", 22);
personAtomicReference.compareAndSet(person, updatePerson);
System.out.println(personAtomicReference.get().getName()); // fanl
System.out.println(personAtomicReference.get().getAge()); // 22
}
2
3
4
5
6
7
8
9
10
上述代码首先创建了一个Person
对象,然后把Person
对象设置进AtomicReference
对象中,然后调用compareAndSet
方法,该方法就是通过CAS
操作设置personAtomicReference
。如果personAtomicReference
的值为person
的话,则将其设置为updatePerson
。实现原理与 AtomicInteger
类中的compareAndSet
方法相同。
AtomicStampedReference
类使用示例
@Test
public void AtomicStampedReferenceDemo() {
// 实例化、取当前值和 stamp值
final Integer initialRef = 0, initialStamp = 0;
final AtomicStampedReference<Integer> asr = new AtomicStampedReference<>(initialRef, initialStamp);
System.out.println("currentValue=" + asr.getReference() + ",currentStamp=" + asr.getStamp()); // currentValue=0,currentStamp=0
// compare and set
final Integer newReference = 666, newStamp = 999;
final boolean casResult = asr.compareAndSet(initialRef,newReference,initialStamp,newStamp);
System.out.println("currentValue=" + asr.getReference() + ",currentStamp=" + asr.getStamp() + ",casResult=" + casResult); // currentValue=666,currentStamp=999,casResult=true
// 获取当前的值和当前的 stamp 值
int[] arr = new int[1];
final Integer currentValue = asr.get(arr);
final int currentStamp = arr[0];
System.out.println("currentValue=" + currentValue + ",currentStamp=" + currentStamp); // currentValue=666,currentStamp=999
// 单独设置 stamp值
final boolean attemptStampResult = asr.attemptStamp(newReference, 88);
System.out.println("currentValue=" + asr.getReference() + ",currentStamp=" + asr.getStamp() + ", attemptStampResult=" + attemptStampResult); // currentValue=666,currentStamp=88, attemptStampResult=true
// 重新设置当前值和 stamp值
asr.set(initialRef, initialStamp);
System.out.println("currentValue=" + asr.getReference() + ",currentStamp=" + asr.getStamp()); // currentValue=0,currentStamp=0
}
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
AtomicMarkableReference
类使用示例
@Test
public void AtomicMarkableReferenceDemo() {
//实例化,取当前值和mark值
final Boolean initialRef = null, initialMark = false;
final AtomicMarkableReference<Boolean> amr = new AtomicMarkableReference<>(initialRef, initialMark);
System.out.println("currentValue=" + amr.getReference() + ",currentMark=" + amr.isMarked()); // currentValue=null,currentMark=false
// compare and set
final Boolean newReference = true, newMark = true;
final boolean casResult = amr.compareAndSet(initialRef, newReference, initialMark, newMark);
System.out.println("currentValue=" + amr.getReference() + ",currentMark=" + amr.isMarked() + ", casResult=" + casResult);// currentValue=true,currentMark=true, casResult=true
// 获取当前的值和当前的 mark值
boolean[] arr = new boolean[1];
final Boolean currentValue = amr.get(arr);
final boolean currentMark = arr[0];
System.out.println("currentValue=" + currentValue + ",currentMark=" + currentMark);// currentValue=true,currentMark=true
// 单独设置 mark值
final boolean attemptMarkResult = amr.attemptMark(newReference, false);
System.out.println("currentValue=" + amr.getReference() + ",currentMark=" + amr.isMarked() + ", attemptMarkResult=" + attemptMarkResult);// currentValue=true,currentMark=false, attemptMarkResult=true
// 重新设置当前值和 mark值
amr.set(initialRef, initialMark);
System.out.println("currentValue=" + amr.getReference() + ",currentMark=" + amr.isMarked());// currentValue=null,currentMark=false
}
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
案例二
// AtomicMarkableReference是将一个boolean值看作是否有更改的标记,本质就是它的版本号只有两个,true和false,修改的时候在这两个版本号之间切换,这样做并不能解决ABA问题,只是会降低ABA问题的发生的几率而已。
public class SolveABAByAtomicMarkableReference {
private static AtomicMarkableReference atomicMarkableReference = new AtomicMarkableReference(100, false);
private static void main(String[] args) {
Thread refT1 = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStaticTrace();
}
atomicMarkableReference.compareAndSet(100, 101, atomicMarkableReference.isMarked(), !atomicMarkableReference.isMarked());
atomicMarkableReference.compareAndSet(101, 100, atomicMarkableReference.isMarked(), !atomicMarkableReference.isMarked())
});
Thread refT2 = new Thread(() -> {
boolean marked = atomicMarkableReference.isMarked();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStaticTrace();
}
boolean c3 = atomicMarkableReference.compareAndSet(100, 101, marked, !marked);
system.out.println(c3); // 返回 true,实际应该返回 false
});
refT1.start();
refT2.start();
}
}
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
31
32
33
# 五、对象的属性修改类型
如果需要原子更新某个类里的某个字段时,需要用到对象的属性修改类型原子类。
■ AtomicIntegerFieldUpdater
:原子更新整型字段的更新器
■ AtomicLongFieldUpdater
:原子更新长整型字段的更新器
■ AtomicReferenceFieldUpdater
:原子更新引用类型里的字段
想原子地更新对象的属性需要两步:第一步,因为对象的属性修改类型原子类都是抽象类,所以每次使用都必须使用静态方法newUpdater()
创建一个更新器,并且需要设置想要更新的类和属性。第二步:更新的对象属性必须使用public volatile
修饰符。
@Test
public void AtomicIntegerFieldUpdateTest() {
AtomicIntegerFieldUpdater<Person> updater = AtomicIntegerFieldUpdater.newUpdater(Person.class, "age");
Person person = new Person("Java", 20);// 20
System.out.println(updater.getAndIncrement(person)); // 21
System.out.println(updater.get(person));
}
class Person {
private String name;
public volatile int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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
31
32