Why synchronizedMap is not enough
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.synchronizedMaplocks each call, so single calls are safe.- A sequence such as
getthenputis 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
Integer n = map.get(sku); // another thread may update here
map.put(sku, n == null ? 1 : n + 1); // lost updateCheck 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.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.