目录
前言
Java 从JDK1.5开始提供了 java.util.concurrent.atomic 包,这个包中的原子操作类提供了一种用法简单、性能高效、线程安全地更新一个变量的方式。在这个包中一共有13个类,属于4种类型的原子更新方式,分别是原子更新基本类型、原子更新数组、原子更新引用和原子更新属性(字段)。
原子更新基本类型类
使用原子的方式更新基本类型,Atomic包提供了以下 3 个类:
- AtomicBoolean:原子更新布尔类型
- AtomicInteger:原子更新整型
- AtomicLong:原子更新长整型
以 AtomicInteger 为例,常用方法如下:
AtomicInteger 与 Integer 的对比
public class AtomicIntegerDemo {
static Integer INTEGER = 0;
static AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
commonInteger();
atomicInteger();
// 睡眠3s,保证程序已经运行完毕
Thread.sleep(3000);
System.out.println("Integer最终运行结果: " + INTEGER);
System.out.println("AtomicInteger最终运行结果: " + ATOMIC_INTEGER);
}
private static void commonInteger() {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
for (int j = 0; j < 500; j++) {
INTEGER++;
}
}).start();
}
}
private static void atomicInteger() {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
for (int j = 0; j < 500; j++) {
ATOMIC_INTEGER.getAndIncrement();
}
}).start();
}
}
}
想要解决 Integer 在并发编程下出现的线程安全问题需要使用 synchronized 关键字
AtomicInteger原理
AtomicInteger 实际上是使用了 volatile 关键字加 CAS 自旋实现线程安全,volatile关键字保证了线程修改变量对其它线程的可见性,CAS 自旋保证了修改操作的原子性。
Unsafe 类
Unsafe 类只提供了以上 3 种 CAS 方法,源码中可以发现实现 AtomicBoolean 是先将 Boolean 转换为整型,再使用 compareAndSwapInt 进行 CAS。
原子更新char、float、和double变量也可以用类似的思路来实现。【Atomic包中没发现有和这几种基本类型有关的类】
原子更新数组
通过原子的方式更新数组里的某个元素,Atomic 包提供了以下 3 个类:
- AtomicIntegerArray:原子更新整型数组里的元素
- AtomicLongArray:原子更新长整型数组里的元素
- AtomicReferenceArray:原子更新引用类型数组里的元素
以AtomicIntegerArray为例,常见方法如下:
AtomicIntegerArray 的使用
public class AtomicIntegerArrayDemo {
static int[] value = new int[]{1, 2, 3, 4, 5};
static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(value);
public static void main(String[] args) {
int oldValue = atomicIntegerArray.getAndAdd(1, 3);
System.out.println("索引 1 处原值: " + oldValue + " 在此基础上加 3 ");
int newValue = atomicIntegerArray.get(1);
System.out.println("索引 1 处新值: " + newValue);
}
}
原子更新引用类型
Atomic包中提供了以下3个类来原子更新引用类型:
- AtomicReference:原子更新引用类型
- AtomicStampedReference:原子更新带有版本号的引用类型
- AtomicMarkableReference:原子更新带有标记位的引用类型
以 AtomicReference 为例,常见方法如下:
AtomicReference 的使用
public class AtomicReferenceDemo {
static AtomicReference<Person> personAtomicReference = new AtomicReference<>();
public static void main(String[] args) {
Person person = new Person("person01", 25);
System.out.println("更新前的person: " + person);
personAtomicReference.set(person);
Person person02 = new Person("person02", 32);
personAtomicReference.compareAndSet(person, person02);
System.out.println("更新后的person: " + personAtomicReference.get());
}
}
@Data
@AllArgsConstructor
class Person {
private String name;
private int age;
}
原子更新字段类
如果需要原子地更新某个类里的某个字段时,就需要使用原子更新字段类,Atomic 包提供了以下3个类进行原子字段更新:
- AtomicIntegerFieldUpdater:原子更新整型字段的更新器
- AtomicLongFieldUpdater:原子更新长整型字段的更新器
- AtomicReferenceUpdater:原子更新引用类型字段的更新器
以 AtomicIntegerFieldUpdater 为例,常用方法如下:
AtomicIntegerFieldUpdater 的使用
public class AtomicIntegerFieldUpdaterDemo {
// 创建更新器,需要关联对象与更新字段
static AtomicIntegerFieldUpdater<Person0> updater = AtomicIntegerFieldUpdater.newUpdater(Person0.class, "age");
public static void main(String[] args) {
Person0 mike = new Person0("Mike", 20);
System.out.println("Mike的年龄为: " + mike.getAge());
System.out.println("3年后...");
boolean flag = updater.compareAndSet(mike, 20, 23);
if (flag) {
System.out.println("Mike的年龄为: " + mike.getAge());
}
}
}
@Data
@AllArgsConstructor
class Person0 {
private String name;
public volatile int age;
}
使用更新器需要两步:第一步,因为原子更新字段类都是抽象类,每次使用的时候必须使用静态方法 newUpdater() 创建一个更新器,并且需要设置想要更新的类和属性。第二步,更新类的字段必须使用 public volatile 修饰符,不然会抛出 ExceptionInInitializerError。