Skip to content
Ameen Abozaid
Planned lessonMID-004-L05

volatile and atomics

  • Lesson 5 of 9
  • Mid-level
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

  • volatile gives visibility and ordering for single reads and writes; not atomic compound actions.
  • Good for flags and safe publication of immutable objects.
  • AtomicInteger, AtomicLong, AtomicReference use compare-and-set for lock-free updates.
  • LongAdder scales better than AtomicLong under heavy contention.
  • Atomics protect one variable; invariants across several variables still need a lock.
Draft outline details

Demonstration

java
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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.