volatile and atomics
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
choose volatile or atomic classes correctly.
Planned topics
volatilegives visibility and ordering for single reads and writes; not atomic compound actions.- Good for flags and safe publication of immutable objects.
AtomicInteger,AtomicLong,AtomicReferenceuse compare-and-set for lock-free updates.LongAdderscales better thanAtomicLongunder heavy contention.- Atomics protect one variable; invariants across several variables still need a lock.
Draft outline details
Demonstration
private final AtomicInteger stock = new AtomicInteger(100);
boolean reserve(int q) {
int cur;
do { cur = stock.get(); if (cur < q) return false; }
while (!stock.compareAndSet(cur, cur - q));
return true;
}Check your understanding
Does volatile int count; count++ fix the race?
Show answer
No; ++ is still three steps.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.