JUC(Java.util.concurrent)包是一组用于并发编程的实用类和接口,它是Java并发API的一部分。在JUC包中,有一系列被称为原子类(Atomic Classes)的类,它们提供了一种无需使用锁即可实现线程安全的方法,用于执行原子操作。
一、基本类型原子类:
如AtomicInteger
、AtomicLong
、AtomicBoolean
,用于原子性地更新基本数据类型。
AtomicInteger 示例及预期结果
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerExample {
private static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) {
// 线程增加计数
for (int i = 0; i < 10; i++) {
new Thread(() -> {
count.incrementAndGet();
System.out.println("Thread " + Thread.currentThread().getId() + ": Count = " + count.get());
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread 27: Count = 4
Thread 30: Count = 7
Thread 32: Count = 9
Thread 24: Count = 1
Thread 33: Count = 10
Thread 31: Count = 8
Thread 28: Count = 5
Thread 26: Count = 3
Thread 25: Count = 2
Thread 29: Count = 6
示例及预期结果的运行结果可能不同的原因主要有以下几点:
-
线程调度:Java虚拟机(JVM)的线程调度器决定了哪个线程将获得CPU时间。不同的调度顺序会导致不同的执行结果。
-
原子操作的实现:
AtomicInteger
内部使用了CAS(Compare-And-Swap)算法来实现原子操作。虽然CAS操作是原子的,但它在不同的CPU架构上的性能可能会有所不同,从而影响执行结果。 -
竞争条件:如果多个线程同时尝试修改
AtomicInteger
的值,可能会发生竞争条件。例如,线程A和线程B同时尝试增加AtomicInteger
的值,可能会导致其中一个线程的更新被另一个线程覆盖,从而影响最终结果。 -
内存可见性:在多线程环境下,为了保证内存的可见性,JVM可能会对共享变量进行额外的内存操作,如写屏障(write barrier)和读屏障(read barrier)。这些操作可能会影响线程的执行顺序,进而影响最终结果。
-
指令重排:为了提高性能,JVM可能会对指令进行重排。这意味着线程的执行顺序可能与代码的顺序不同,从而影响最终结果。
AtomicLong 示例及预期结果
import java.util.concurrent.atomic.AtomicLong;
public class AtomicLongExample {
private static AtomicLong sequenceNumber = new AtomicLong(0);
public static void main(String[] args) {
// 线程生成序列号
for (int i = 0; i < 10; i++) {
new Thread(() -> {
long seq = sequenceNumber.incrementAndGet();
System.out.println("Thread " + Thread.currentThread().getId() + ": Sequence Number = " + seq);
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread 31: Sequence Number = 8
Thread 33: Sequence Number = 10
Thread 27: Sequence Number = 4
Thread 25: Sequence Number = 2
Thread 28: Sequence Number = 5
Thread 30: Sequence Number = 7
Thread 29: Sequence Number = 6
Thread 26: Sequence Number = 3
Thread 24: Sequence Number = 1
Thread 32: Sequence Number = 9
AtomicBoolean 示例及预期结果
import java.util.concurrent.atomic.AtomicBoolean;
public class AtomicBooleanExample {
private static AtomicBoolean flag = new AtomicBoolean(false);
public static void main(String[] args) {
// 线程1尝试将flag设置为true
new Thread(() -> {
flag.compareAndSet(false, true);
System.out.println("Thread 1: Flag set to true.");
}).start();
// 线程2尝试将flag设置为false
new Thread(() -> {
flag.compareAndSet(true, false);
System.out.println("Thread 2: Flag set to false.");
}).start();
}
}
运行结果:
Thread 1: Flag set to true.
Thread 2: Flag set to false.
二、数组类型原子类:
如AtomicIntegerArray
、AtomicLongArray
、AtomicReferenceArray
,用于原子性地更新数组。
AtomicIntegerArray 示例及预期结果
import java.util.concurrent.atomic.AtomicIntegerArray;
public class AtomicIntegerArrayExample {
private static AtomicIntegerArray array = new AtomicIntegerArray(new int[]{1, 2, 3});
public static void main(String[] args) {
// 线程更新数组元素
for (int i = 0; i < array.length(); i++) {
final int index = i;
new Thread(() -> {
array.getAndAdd(index, 5);
System.out.println("Thread " + Thread.currentThread().getId() + ": Array[" + index + "] = " + array.get(index));
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread 26: Array[2] = 8
Thread 24: Array[0] = 6
Thread 25: Array[1] = 7
AtomicLongArray 示例
import java.util.concurrent.atomic.AtomicLongArray;
public class AtomicLongArrayExample {
public static void main(String[] args) {
AtomicLongArray array = new AtomicLongArray(new long[]{1L, 2L, 3L});
// 创建多个线程,每个线程更新数组中的元素
for (int i = 0; i < 10; i++) {
final int index = i % 3; // 使用 % 操作符确保索引不会超过数组长度
new Thread(() -> {
array.getAndAdd(index, 5L);
System.out.println("Thread " + Thread.currentThread().getId() + ": Array[" + index + "] = " + array.get(index));
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread 24: Array[0] = 16
Thread 25: Array[1] = 17
Thread 33: Array[0] = 21
Thread 32: Array[2] = 18
Thread 26: Array[2] = 13
Thread 30: Array[0] = 16
Thread 27: Array[0] = 16
Thread 28: Array[1] = 17
Thread 31: Array[1] = 17
Thread 29: Array[2] = 13
AtomicReferenceArray 示例
import java.util.concurrent.atomic.AtomicReferenceArray;
public class AtomicReferenceArrayExample {
public static void main(String[] args) {
AtomicReferenceArray<String> array = new AtomicReferenceArray<>(new String[]{"A", "B", "C"});
// 创建多个线程,每个线程更新数组中的元素
for (int i = 0; i < 10; i++) {
final int index = i % 3;
new Thread(() -> {
array.getAndSet(index, "X");
System.out.println("Thread " + Thread.currentThread().getId() + ": Array[" + index + "] = " + array.get(index));
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread 32: Array[2] = X
Thread 25: Array[1] = X
Thread 24: Array[0] = X
Thread 30: Array[0] = X
Thread 27: Array[0] = X
Thread 31: Array[1] = X
Thread 29: Array[2] = X
Thread 28: Array[1] = X
Thread 26: Array[2] = X
Thread 33: Array[0] = X
三、引用类型原子类:
如AtomicReference
、AtomicStampedReference
、AtomicMarkableReference
,用于原子性地更新对象引用。
AtomicReference 示例
import java.util.concurrent.atomic.AtomicReference;
public class AtomicReferenceExample {
public static void main(String[] args) {
AtomicReference<String> ref = new AtomicReference<>("A");
// 创建多个线程,每个线程更新引用
for (int i = 0; i < 10; i++) {
final int threadId = i;
new Thread(() -> {
ref.compareAndSet("A", "B");
System.out.println("Thread " + threadId + ": Updated reference to B");
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread 8: Updated reference to B
Thread 0: Updated reference to B
Thread 3: Updated reference to B
Thread 6: Updated reference to B
Thread 2: Updated reference to B
Thread 1: Updated reference to B
Thread 4: Updated reference to B
Thread 7: Updated reference to B
Thread 5: Updated reference to B
Thread 9: Updated reference to B
AtomicStampedReference 示例
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;
public class AtomicStampedReferenceExample {
public static void main(String[] args) {
// 创建一个 AtomicStampedReference,初始值为 "A" 和版本号为 0
AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
CountDownLatch countDownLatch = new CountDownLatch(1);
// 创建一个线程,尝试将对象引用更新为 "B",并增加版本号
new Thread(() -> {
int stamp = ref.getStamp();
System.out.println("Thread 1: Current stamp = " + stamp);
if (ref.compareAndSet("A", "B", stamp, stamp + 1)) {
System.out.println("Thread 1: Object reference updated to B" + ref.getStamp());
} else {
System.out.println("Thread 1: Object reference update failed");
}
countDownLatch.countDown();
}).start();
// 创建另一个线程,尝试将对象引用更新回 "A",并减少版本号
new Thread(() -> {
try {
countDownLatch.await();
}catch (InterruptedException e) {
throw new RuntimeException(e);
}
int stamp = ref.getStamp();
System.out.println("Thread 2: Current stamp = " + stamp);
if (ref.compareAndSet("B", "A", stamp, stamp - 1)) {
System.out.println("Thread 2: Object reference updated back to A" + ref.getStamp());
} else {
System.out.println("Thread 2: Object reference update failed" + ref.getStamp());
}
}).start();
}
}
运行结果(具体顺序可能不同): 使用了CountDownLatch保证线程的执行顺序
Thread 1: Current stamp = 0
Thread 1: Object reference updated to B1
Thread 2: Current stamp = 1
Thread 2: Object reference updated back to A0
AtomicMarkableReference 示例
import java.util.concurrent.atomic.AtomicMarkableReference;
public class AtomicReferenceExample {
public static void main(String[] args) {
// 创建一个AtomicMarkableReference,用于原子性地更新对象引用
AtomicMarkableReference<String> ref = new AtomicMarkableReference<>("A", false);
// 创建一个线程,尝试将对象引用更新为"B"
new Thread(() -> {
if (ref.compareAndSet("A", "B", false, true)) {
System.out.println("Thread 1: Object reference updated to B");
} else {
System.out.println("Thread 1: Object reference update failed");
}
}).start();
// 创建另一个线程,尝试将对象引用更新回"A"
new Thread(() -> {
if (ref.compareAndSet("B", "A", true, false)) {
System.out.println("Thread 2: Object reference updated back to A");
} else {
System.out.println("Thread 2: Object reference update failed");
}
}).start();
}
}
运行结果:
Thread 1: Object reference updated to B
Thread 2: Object reference updated back to A
四、对象的字段原子类:(对象的属性修改原子类):
如AtomicIntegerFieldUpdater
、AtomicLongFieldUpdater
、AtomicReferenceFieldUpdater
,用于更新对象的字段。
用于原子性地更新对象的字段。这些类特别适用于解决 ABA 问题,即一个字段在两个线程之间传递,第一个线程将其从 A 变为 B,第二个线程将其从 B 变为 C,然后第一个线程再次将其从 C 变为 A。在这种情况下,如果只是比较字段值而不检查其他条件,可能会导致错误的结果。
示例代码:
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
public class AtomicFieldUpdaterExample {
public static class MyObject {
private volatile int value=11;
private static final AtomicIntegerFieldUpdater<MyObject> intUpdater = AtomicIntegerFieldUpdater.newUpdater(MyObject.class, "value");
private volatile long longValue=17L;
private static final AtomicLongFieldUpdater<MyObject> longUpdater = AtomicLongFieldUpdater.newUpdater(MyObject.class, "longValue");
private volatile String referenceValue = "A"; // 设置一个明确的初始值
private static final AtomicReferenceFieldUpdater<MyObject, String> refUpdater = AtomicReferenceFieldUpdater.newUpdater(MyObject.class, String.class, "referenceValue");
}
public static void main(String[] args) {
MyObject obj = new MyObject();
// 使用 AtomicIntegerFieldUpdater 更新 int 字段
new Thread(() -> {
System.out.println(MyObject.intUpdater.get(obj));
if (MyObject.intUpdater.compareAndSet(obj, 0, 1)) {
System.out.println("Thread 1: Incremented int value");
} else {
System.out.println("Thread 1: int value was already 1");
}
}).start();
// 使用 AtomicLongFieldUpdater 更新 long 字段
new Thread(() -> {
System.out.println(MyObject.longUpdater.get(obj));
if (MyObject.longUpdater.compareAndSet(obj, 0L, 1L)) {
System.out.println("Thread 2: Incremented long value");
} else {
System.out.println("Thread 2: long value was already 1");
}
}).start();
// 使用 AtomicReferenceFieldUpdater 更新 String 字段
new Thread(() -> {
System.out.println(MyObject.refUpdater.get(obj));
if (MyObject.refUpdater.compareAndSet(obj, "A", "B")) {
System.out.println("Thread 3: Updated reference value to B");
} else {
System.out.println("Thread 3: Update failed");
}
}).start();
}
}
运行结果;
11
Thread 1: int value was already 1
17
Thread 2: long value was already 1
A
Thread 3: Updated reference value to B
五、累加器:
如 LongAdder
、DoubleAdder
。
LongAdder
和 DoubleAdder
是 Java 8 引入的两个类,用于在高并发场景下进行累加操作。它们都使用了一种称为“累加器”的机制,这使得在高并发场景下可以避免不必要的线程阻塞和竞争。
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.atomic.DoubleAdder;
public class AdderExample {
public static void main(String[] args) {
// 使用 LongAdder 进行累加操作
LongAdder longAdder = new LongAdder();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
longAdder.increment();
}
System.out.println("Thread LongAdder" + Thread.currentThread().getId() + ": Sum = " + longAdder.sum());
}).start();
}
// 使用 DoubleAdder 进行累加操作
DoubleAdder doubleAdder = new DoubleAdder();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
doubleAdder.add(1.0);
}
System.out.println("Thread DoubleAdder" + Thread.currentThread().getId() + ": Sum = " + doubleAdder.sum());
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread LongAdder31: Sum = 9531
Thread LongAdder27: Sum = 9441
Thread LongAdder28: Sum = 9187
Thread LongAdder29: Sum = 10000
Thread LongAdder26: Sum = 8719
Thread LongAdder30: Sum = 8898
Thread LongAdder25: Sum = 9582
Thread LongAdder33: Sum = 9802
Thread LongAdder32: Sum = 5365
Thread LongAdder24: Sum = 8868
Thread DoubleAdder41: Sum = 8031.0
Thread DoubleAdder37: Sum = 6973.0
Thread DoubleAdder42: Sum = 9814.0
Thread DoubleAdder35: Sum = 4861.0
Thread DoubleAdder40: Sum = 10000.0
Thread DoubleAdder38: Sum = 7266.0
Thread DoubleAdder39: Sum = 7951.0
Thread DoubleAdder34: Sum = 8984.0
Thread DoubleAdder36: Sum = 5176.0
Thread DoubleAdder43: Sum = 9937.0
注意:volatile解决多线程内存中不可见问题,对于一写多读,可以使用变量同步问题,但是如果多写,同样无法解决线程的安全问题。对于 ++ 操作,在JDK版本8使用LongAdder比使用AtomicLong的性能更好(减少乐观锁的重试次数)
LongAdder原理分析
-
分段存储:
LongAdder
的核心是一个名为cells
的数组,数组中的每个元素都是一个Cell
对象。Cell
对象类似于一个AtomicLong
,用于存储累加值。cells
数组的大小在创建LongAdder
时可以指定,默认大小为1
。 -
自旋锁:
LongAdder
中的每个Cell
对象都使用了一个简单的自旋锁(casBaseline()
)来保护其累加值。这意味着当一个线程访问某个Cell
对象时,它会尝试获取该对象的锁。如果锁已经被其他线程持有,线程会进行自旋,直到锁被释放。 -
全局累加器:除了
cells
数组,LongAdder
还有一个名为base
的变量,用于存储累加器的全局值。这个全局值会在初始化时被设置,并且在后续的操作中不再被修改。 -
更新策略:当一个线程需要更新累加值时,它会先尝试更新
base
变量。如果更新成功,则累加操作完成。如果更新失败(即base
变量已经被其他线程修改),线程会尝试更新cells
数组中的一个Cell
对象。如果这个操作成功,则累加操作完成。如果这个操作也失败,线程会尝试更新另一个Cell
对象,以此类推。 -
合并累加器:在某些情况下,当
cells
数组中的Cell
对象被修改后,LongAdder
会合并这些修改,以确保base
变量和cells
数组中的值是一致的。 -
查询策略:当一个线程需要查询累加值时,它会首先查询
base
变量。如果base
变量已经被修改,线程会查询cells
数组中的所有Cell
对象,并将它们的值加到base
变量上,然后返回这个总和。
六、积累器:
如 LongAccumulator
、DoubleAccumulator
。
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.DoubleAccumulator;
public class AccumulatorExample {
public static void main(String[] args) {
// 使用 LongAccumulator 进行累加操作
LongAccumulator longAccumulator = new LongAccumulator((a, b) -> a + b, 0L);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
longAccumulator.accumulate(1L);
}
System.out.println("Thread LongAccumulator" + Thread.currentThread().getId() + ": Sum = " + longAccumulator.get());
}).start();
}
// 使用 DoubleAccumulator 进行累加操作
DoubleAccumulator doubleAccumulator = new DoubleAccumulator((a, b) -> a + b, 0.0);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
doubleAccumulator.accumulate(1.0);
}
System.out.println("Thread DoubleAccumulator" + Thread.currentThread().getId() + ": Sum = " + doubleAccumulator.get());
}).start();
}
}
}
运行结果(具体顺序可能不同):
Thread LongAccumulator32: Sum = 9495
Thread LongAccumulator29: Sum = 9441
Thread LongAccumulator25: Sum = 10000
Thread LongAccumulator28: Sum = 9449
Thread LongAccumulator24: Sum = 9717
Thread LongAccumulator26: Sum = 9490
Thread LongAccumulator30: Sum = 9478
Thread LongAccumulator33: Sum = 6452
Thread LongAccumulator31: Sum = 9177
Thread LongAccumulator27: Sum = 6515
Thread DoubleAccumulator38: Sum = 9413.0
Thread DoubleAccumulator34: Sum = 8719.0
Thread DoubleAccumulator39: Sum = 8353.0
Thread DoubleAccumulator35: Sum = 7441.0
Thread DoubleAccumulator37: Sum = 10000.0
Thread DoubleAccumulator40: Sum = 8108.0
Thread DoubleAccumulator36: Sum = 8353.0
Thread DoubleAccumulator41: Sum = 6961.0
Thread DoubleAccumulator43: Sum = 7782.0
Thread DoubleAccumulator42: Sum = 7709.0