Advanced 12 min

Threads, shared state, and atomicity

Concurrent tasks may take turns in the middle of an operation, so shared changes need coordination.

How it works

Write out two possible schedules side by side. In one, the first thread completes the increment before the second reads. In the other, both threads read before either writes. Only the second schedule loses work. An atomic operation makes the update indivisible to the other thread.

Walk through an example

count++ reads, adds, and writes. If two threads both read 0 before either writes, both can write 1. An AtomicInteger combines its increment into one atomic operation.

What to watch for

Making an ordinary integer volatile improves visibility but does not make an increment atomic. Match the synchronization method to the whole operation you need to protect.

Code example

public class Main {
    public static void main(String[] args) {
        var count = new java.util.concurrent.atomic.AtomicInteger();
        count.incrementAndGet();
        count.incrementAndGet();
        System.out.println(count.get());
    }
}

Check your understanding

What total should two successful atomic increments leave?

See the example and explanation
Worked example
Given Two threads each increment a shared counter starting at 0.
Answer 2

One increment changes 0 to 1 and the other changes 1 to 2. Each sees the latest atomic value.

Open practice problem
Next lessonCombining asynchronous results