AtomicLongFieldUpdater Updates Volatile Fields
Update volatile long fields without AtomicLong objects through AtomicLongFieldUpdater, using compareAndSet and incrementAndGet.
Code
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
public class FieldUpdaterDemo {
static class Job {
// 字段必须是 volatile,updater 通过类与字段名创建
volatile long processed;
volatile long failed;
}
private static final AtomicLongFieldUpdater<Job> PROCESSED =
AtomicLongFieldUpdater.newUpdater(Job.class, "processed");
public static void main(String[] args) throws Exception {
Job job = new Job();
Thread[] workers = new Thread[4];
for (int t = 0; t < workers.length; t++) {
workers[t] = new Thread(() -> {
for (int i = 0; i < 250; i++) {
PROCESSED.incrementAndGet(job);
}
});
workers[t].start();
}
for (Thread worker : workers) {
worker.join();
}
System.out.println("processed: " + PROCESSED.get(job));
// compareAndSet 以当前值做一次条件更新
long current = PROCESSED.get(job);
boolean swapped = PROCESSED.compareAndSet(job, current, current + 1);
System.out.println("cas applied: " + swapped);
System.out.println("after cas: " + PROCESSED.get(job));
// 同一个类可以创建多个字段的 updater
AtomicLongFieldUpdater<Job> failed =
AtomicLongFieldUpdater.newUpdater(Job.class, "failed");
failed.addAndGet(job, 3);
System.out.println("failed: " + failed.get(job));
}
}Inside the snippet
AtomicLongFieldUpdater Updates Volatile Fields keeps everything in the classes FieldUpdaterDemo and Job.
Repetition is confined to for (int t = 0; t < workers.length; t++) — the rest of the file is straight-line.
Putting it to use
The demo output is labeled (processed:, cas applied:, after cas:), so each printed line points back to the operation that produced it.
Core lines
Thread[] workers = new Thread[4];
workers[t] = new Thread(() -> {
for (int i = 0; i < 250; i++) {
PROCESSED.incrementAndGet(job);
}
});
for (Thread worker : workers) {
worker.join();
}
Interactive Tools for This Topic
FAQ
- What does AtomicLongFieldUpdater Updates Volatile Fields print when run?
- Running the file directly is enough — expect labeled output lines such as `processed:`, `cas applied:`, `after cas:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.