← 中文资源

简体中文版本

AtomicIntegerArray 按元素 CAS

用 AtomicIntegerArray 做分片计数:每个元素独立走 CAS 自旋递增,失败重读重试,线程只争用自己那一格,整体无锁。

阅读英文原文

实现说明

AtomicIntegerArray 按元素 CAS可以归结为类 ShardedCounter和函数 increment。 在这里做循环的是 for (int w = 0; w < workers.length; w++)。

使用要点

  • 跑完文件,输出里会留下标记——total =、shard0 =。
  • 运行整个文件:main 会依次驱动 increment。

常见问题

运行「AtomicIntegerArray 按元素 CAS」会打印什么?

运行文件本身,total =、shard0 = 这些前缀各对应一段演示逻辑。

主签名形如 static void increment(AtomicIntegerArray array, int slot)

核心语句

Thread[] workers = new Thread[4];
workers[w] = new Thread(() -> {
    for (int i = 0; i < 100; i++) {
        increment(slots, id % 2);
    }
});
for (Thread worker : workers) {
    worker.join();
}

代码示例

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicIntegerArray;

public class ShardedCounter {

    // CAS 自旋递增:失败就重读旧值重试,直到成功
    static void increment(AtomicIntegerArray array, int slot) {
        int seen;
        do {
            seen = array.get(slot);
        } while (!array.compareAndSet(slot, seen, seen + 1));
    }

    public static void main(String[] args) throws InterruptedException {
        // 4 个线程只写 2 个分片:CAS 循环会真实经历争用与重试
        AtomicIntegerArray slots = new AtomicIntegerArray(16);
        Thread[] workers = new Thread[4];
        for (int w = 0; w < workers.length; w++) {
            final int id = w;
            workers[w] = new Thread(() -> {
                for (int i = 0; i < 100; i++) {
                    increment(slots, id % 2);
                }
            });
            workers[w].start();
        }
        for (Thread worker : workers) {
            worker.join();
        }

        int total = 0;
        int used = 0;
        for (int i = 0; i < slots.length(); i++) {
            total += slots.get(i);
            if (slots.get(i) > 0) {
                used++;
            }
        }
        System.out.println("total = " + total + ", used slots = " + used);
        System.out.println("shard0 = " + slots.get(0) + ", shard1 = " + slots.get(1));
    }
}