1. Concept library
  2. Java & Spring Boot
  3. Module 4: Concurrency

Concept

Threads and thread safety

Running work on several threads, the races that follow, and the tools that prevent them.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a race condition is with the count++ example
  2. Write code that runs work on several threads and collects the result
  3. Fix a race with AtomicInteger or synchronisation

In practice

A few lines that show Threads and thread safety doing its job.

Java
var counter = new AtomicInteger();
var unsafe = new int[1];

try (var pool = Executors.newFixedThreadPool(8)) {
    for (int i = 0; i < 10_000; i++) {
        pool.submit(() -> { counter.incrementAndGet(); unsafe[0]++; });
    }
}
System.out.println(counter.get());   // 10000
System.out.println(unsafe[0]);       // usually less: lost updates

The common mistake

Watch for

Treating count++ as one operation. It is a read, an add and a write, and another thread can slip in between them. Use AtomicInteger or synchronise the update.

What to know first

Your roadmap puts these before Threads and thread safety, unless you already know them.

How it stays learned

Once a session shows you understand Threads and thread safety, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Threads and thread safety.

Next in the moduleJava memory model →