AtomicIntegerArray通过Unsafe类和CAS指令实现线程安全的int数组元素更新,不暴露CAS方法,仅提供compareAndSet等原子操作;基于内存偏移地址定位元素,调用Unsafe.compareAndSwapInt完成原子更新。

AtomicIntegerArray 通过内部封装的 Unsafe 类和 CAS(Compare-And-Swap)指令实现线程安全的数组元素更新,**不直接暴露 CAS 方法**,而是提供一系列以 compareAndSet 命名的原子操作方法。
核心机制:底层依赖 Unsafe.compareAndSwapInt
AtomicIntegerArray 在初始化时会计算每个数组元素在内存中的偏移地址(基于数组首地址 + 索引 × 元素大小)。每次调用 compareAndSet(int i, int expect, int update) 时,它会:
- 根据索引
i定位到该元素对应的内存地址 - 调用
Unsafe.compareAndSwapInt(array, offset, expect, update) - 若当前值等于
expect,则原子更新为update,并返回true;否则返回false
常用 CAS 相关方法
所有操作都基于索引,而非引用:
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
-
boolean compareAndSet(int i, int expect, int update):标准 CAS,成功返回 true -
int getAndSet(int i, int newValue):设置新值并返回旧值(非 CAS,但原子) -
int getAndIncrement(int i)、incrementAndGet(int i)等:内部也使用循环 CAS 实现自增 -
weakCompareAndSet(int i, int expect, int update):语义更弱(不保证 happens-before),一般场景推荐用compareAndSet
典型使用示例
比如实现一个线程安全的计数器数组:
AtomicIntegerArray counts = new AtomicIntegerArray(10);
// 尝试将索引 3 的值从 5 更新为 6
boolean success = counts.compareAndSet(3, 5, 6);
if (!success) {
// 当前值不是 5,可能被其他线程改过,可重试或处理冲突
int current = counts.get(3);
System.out.println("CAS 失败,当前值:" + current);
}
注意事项
- 数组长度在构造后不可变,且 AtomicIntegerArray 不包装原始数组,修改原数组不影响它
- CAS 是乐观策略,失败需由调用方决定是否重试(如配合 while 循环实现无锁更新)
- 不能对整个数组做原子操作,每个元素独立 CAS
- 不支持 null 或对象引用,仅适用于
int类型数组
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










