Quick revision
The short answer
No. Collections.synchronizedMap makes each method call synchronized, but containsKey followed by put is two calls, so two threads can both find the key missing and both put. We fix it by holding the map's own lock around the compound action, synchronized (m) { ... }, or by using the single atomic call m.putIfAbsent(k, 1). Iteration over m, or over its keySet, values or entrySet views, must also happen inside synchronized (m), otherwise a concurrent change can throw ConcurrentModificationException. ConcurrentHashMap avoids both problems: it offers atomic putIfAbsent, compute and merge, and its iterators are safe without external locking.
What to remember
In this answer, we saw that Collections.synchronizedMap only makes each method call synchronized, so the containsKey then put sequence is a check-then-act race where two threads can both put. We fixed it by synchronizing on the wrapper itself around the compound action, or by using the atomic putIfAbsent. Iteration over the map or its views must also be inside synchronized (m), or it can throw ConcurrentModificationException, and copying under the lock keeps that short. ConcurrentHashMap removes both problems with atomic putIfAbsent, compute and merge and with iterators that need no external lock.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
No. Collections.synchronizedMap makes each method call synchronized, but containsKey followed by put is two calls, so two threads can both find the key missing and both put. We fix it by holding the map's own lock around the compound action, synchronized (m) { ... }, or by using the single atomic call m.putIfAbsent(k, 1). Iteration over m, or over its keySet, values or entrySet views, must also happen inside synchronized (m), otherwise a concurrent change can throw ConcurrentModificationException. ConcurrentHashMap avoids both problems: it offers atomic putIfAbsent, compute and merge, and its iterators are safe without external locking.
Why this question is asked
Collections.synchronizedMap is often the first tool people use to make a map thread-safe, and the name suggests it solves the problem completely. It does not, and the gap shows up as rare duplicate work, lost updates and occasional ConcurrentModificationException in production logs. Interviewers ask this question because it checks two related ideas at once: that thread safety of individual methods does not compose into thread safety of sequences, and that iteration is itself a sequence of calls. In this answer, we will recap what the wrapper does, reproduce the race, fix it two ways, show the iteration rule, and compare with ConcurrentHashMap.
1A Quick Recap of the Synchronized Wrapper
Collections.synchronizedMap(map) returns a wrapper object. Every method of the wrapper takes a lock, by default the wrapper object itself, calls the same method on the underlying HashMap, and releases the lock. So no two threads can be inside the map's methods at the same time, and the HashMap can never be corrupted by concurrent puts.
That is the whole guarantee: one method call at a time. The wrapper cannot know that our containsKey and our put belong together, so it releases the lock between them like between any two calls.
2Why the Snippet Is Not Thread-Safe
The code makes a decision based on one call and acts on it with another. Between them, the lock is free, and another thread can do exactly the same thing.
6 messages in order. Play them, or step through them one at a time.
In this exact snippet both threads put 1, so the final map looks right, which is why the bug hides. But the pattern is dangerous as soon as the action matters: if the put stores a newly created session, connection or counter, the second put replaces the first thread's object, and any work done with it is lost. And if the value were a count, the first thread's update would be overwritten. This is the classic check-then-act race.
3Fix 1: Hold the Map's Lock for the Compound Action
The wrapper's methods synchronize on the wrapper object itself. So if we synchronize on the same object, our whole block excludes every other thread's map calls for its duration. This is documented behaviour, which is what makes it safe to rely on.
Notice that locking on any other object would not help, because the wrapper's own calls from other threads would not wait for it. The block must be short, since every other user of the map waits while we hold it.
4Fix 2: One Atomic Call
Since Java 8, the Map interface has default methods that express common compound actions as a single call, and the synchronized wrapper overrides them to run under its lock. putIfAbsent puts only if the key is absent and returns the existing value otherwise.
One call means one lock acquisition, so the race is gone. computeIfAbsent, compute and merge are also available for more complex updates, and on the synchronized wrapper they run under the wrapper's lock too.
5Iterating Safely
Iteration is a long sequence of calls: hasNext, next, hasNext, next. The wrapper locks each individual call, but between them another thread can put or remove, and the underlying HashMap iterator detects the change and throws ConcurrentModificationException. The Javadoc of synchronizedMap is explicit that we must synchronize on the map while iterating over it or any of its collection views.
Notice the cost of the right version: the whole map is locked for the duration of the loop. If the loop body is slow, every other thread waits. Copying under the lock and processing the copy outside keeps the lock short, at the price of working on a snapshot.
6How ConcurrentHashMap Avoids Both Problems
ConcurrentHashMap was designed for concurrent use, so the common compound actions are atomic methods: putIfAbsent, computeIfAbsent, compute and merge each lock only the key's bin while they run. Its iterators are weakly consistent: they never throw ConcurrentModificationException, never need an external lock, and may or may not show changes made during the loop. Reads take no lock at all. So the snippet becomes a single map.putIfAbsent(k, 1) or merge, and iteration is a plain for loop. The one thing it cannot do is let us lock the whole map across several calls, which is the remaining reason to choose the wrapper.
7Follow-up questions
Which object does synchronizedMap lock on?
By default the wrapper object itself, which is why synchronized (m) works. There is no public overload of synchronizedMap that takes a custom lock object, so the only reliable lock for compound actions is the wrapper you got back. Do not synchronize on the underlying HashMap, which nobody else locks.
Is size() followed by get() also a problem?
Yes, any sequence where a later call depends on the result of an earlier one is a compound action. For example checking isEmpty and then reading an entry can fail if another thread removes the last entry in between. Hold the lock for the whole sequence or use a single atomic method.
Is iterating ConcurrentHashMap without a lock really safe?
Yes. It will not throw and will not return corrupted entries. The only difference from a locked iteration is consistency: concurrent changes during the loop may or may not be visible, so totals computed by iterating are approximate while writers are active.
8Conclusion
In this answer, we saw that Collections.synchronizedMap only makes each method call synchronized, so the containsKey then put sequence is a check-then-act race where two threads can both put. We fixed it by synchronizing on the wrapper itself around the compound action, or by using the atomic putIfAbsent. Iteration over the map or its views must also be inside synchronized (m), or it can throw ConcurrentModificationException, and copying under the lock keeps that short. ConcurrentHashMap removes both problems with atomic putIfAbsent, compute and merge and with iterators that need no external lock.
Open with
No, it isn't thread-safe. synchronizedMap only makes each individual method call synchronized. containsKey and put are two separate calls, and the lock is released between them, so two threads can both see the key missing and both put.
Then, if they want more
Here both put 1, so it might look harmless, but if the value were a new object or a count, one thread's work would overwrite the other's. That's a check-then-act race. There are two fixes.
I can synchronize on the map itself, synchronized on m, around the check and the put, because the wrapper's methods use the wrapper object as their lock, so my block excludes all other calls. Or I use a single atomic call, putIfAbsent of k and 1, which runs under the lock in one go.
For iteration, the Javadoc says you have to manually synchronize on the map while iterating it or any of its views, keySet, values or entrySet, because iteration is many calls, and if another thread modifies the map in between, the HashMap iterator throws ConcurrentModificationException.
That means the whole map is locked during the loop, so if the work is slow I'd copy the keys under the lock and process the copy outside. In practice, I'd just use ConcurrentHashMap. It has atomic putIfAbsent, compute and merge, its iterators are weakly consistent and never throw, and I don't need any external lock to iterate.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Is this thread-safe?": https://scrivio-interview-library.netlify.app/java/concurrent-collections/ca19050de5/