Skip to content
Ameen Abozaid
Planned lessonMID-005-L01

Why synchronizedMap is not enough

  • Lesson 1 of 5
  • 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

see why per-call locking does not make compound actions safe.

Planned topics

  • Collections.synchronizedMap locks each call, so single calls are safe.
  • A sequence such as get then put is two calls; another thread can run between them.
  • Iterating needs manual locking on the map, or you risk ConcurrentModificationException.
  • One lock for the whole map limits throughput.
  • Use collections designed for concurrency.
Draft outline details

Demonstration

java
Integer n = map.get(sku);             // another thread may update here
map.put(sku, n == null ? 1 : n + 1);  // lost update

Check your understanding

Why is get then put unsafe on a synchronized map?

Show answer

The pair is not atomic; another thread can interleave.

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.