Per Element CAS With AtomicIntegerArray
Update individual array elements with compareAndSet retry loops so several threads can bump counters in one array without locking the whole.
Code
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));
}
}Things the file does, in order
Count the class ShardedCounter and the function increment as the entire surface area of Per Element CAS With AtomicIntegerArray.
One loop does the cycling here: for (int w = 0; w < workers.length; w++).
Putting it to use
Entry signature: static void increment(AtomicIntegerArray array, int slot)
Running the file prints labeled results such as total =, shard0 = — each operation’s effect is visible in the output.
main is the driver: it invokes increment before returning.
Core lines
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();
}
Interactive Tools for This Topic
FAQ
- What does Per Element CAS With AtomicIntegerArray print when run?
- Execute the whole file; each printed line is prefixed with a label like `total =`, `shard0 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.