Java
ConcurrentHashMap
Atomicity
Concurrency
Thread-Safety

Java ConcurrentHashMap actions atomicity

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

ConcurrentHashMap is thread-safe, but that does not mean every sequence of operations on it is atomic. Many production bugs come from assuming that a map designed for concurrency automatically makes multi-step logic safe.

What Atomicity Means Here

An operation is atomic when other threads cannot observe it halfway through. With ConcurrentHashMap, many single-map operations are atomic for one key, but a hand-written series of operations is usually not.

Safe atomic methods include operations such as putIfAbsent, remove(key, value), replace(key, oldValue, newValue), compute, computeIfAbsent, computeIfPresent, and merge.

For example, this is atomic:

java
1import java.util.concurrent.ConcurrentHashMap;
2
3public class PutIfAbsentExample {
4    public static void main(String[] args) {
5        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
6        String previous = map.putIfAbsent("status", "created");
7
8        System.out.println(previous);      // null
9        System.out.println(map.get("status")); // created
10    }
11}

If two threads call putIfAbsent for the same key, only one wins.

Compound Logic Is Usually Not Atomic

This pattern is not safe:

java
if (!map.containsKey("count")) {
    map.put("count", 1);
}

Two threads can both see that the key is missing and both call put. The final state may still contain one value, but the logic was raced.

Use computeIfAbsent instead:

java
1import java.util.concurrent.ConcurrentHashMap;
2
3public class ComputeIfAbsentExample {
4    public static void main(String[] args) {
5        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
6
7        Integer value = map.computeIfAbsent("count", key -> 1);
8
9        System.out.println(value);
10        System.out.println(map.get("count"));
11    }
12}

The entire check-and-insert step happens atomically for that key.

Updating Existing Values Safely

If multiple threads update numeric values, use atomic map methods together with thread-friendly value types.

java
1import java.util.concurrent.ConcurrentHashMap;
2import java.util.concurrent.atomic.LongAdder;
3
4public class CounterExample {
5    public static void main(String[] args) {
6        ConcurrentHashMap<String, LongAdder> counters = new ConcurrentHashMap<>();
7
8        counters.computeIfAbsent("requests", key -> new LongAdder()).increment();
9        counters.computeIfAbsent("requests", key -> new LongAdder()).increment();
10
11        System.out.println(counters.get("requests").sum());
12    }
13}

This pattern scales better than repeatedly reading an Integer, incrementing it, and writing it back.

compute and merge Are Often the Right Tools

When the new value depends on the old one, compute and merge express that safely.

java
1import java.util.concurrent.ConcurrentHashMap;
2
3public class MergeExample {
4    public static void main(String[] args) {
5        ConcurrentHashMap<String, Integer> totals = new ConcurrentHashMap<>();
6
7        totals.merge("apples", 3, Integer::sum);
8        totals.merge("apples", 4, Integer::sum);
9
10        System.out.println(totals.get("apples")); // 7
11    }
12}

That read-modify-write cycle is atomic for the specific key.

What Is Not Guaranteed

There are several limits worth remembering.

Iteration is weakly consistent, not a locked snapshot. A loop over the map can observe entries that were added or removed while iteration is in progress.

java
for (String key : map.keySet()) {
    System.out.println(key);
}

This is safe in the sense that it will not throw ConcurrentModificationException, but it does not mean the iteration sees one frozen moment in time.

Also, atomicity is typically per key, not across multiple keys. If you need to update fromAccount and toAccount as one indivisible transaction, ConcurrentHashMap alone is not enough. You need a higher-level lock or transactional design.

Finally, a thread-safe map does not make mutable values thread-safe. If the map stores ArrayList instances and several threads modify the same list, you still have a race inside the value object.

Bulk Operations and Observability

Methods such as forEach, search, and reduce are designed for concurrent access, but they are not transactional snapshots either. Use them when approximate or weakly consistent traversal is acceptable.

For monitoring counters, caches, and deduplicated registries, that is usually fine. For money movement or cross-record invariants, it is not.

Common Pitfalls

Assuming thread-safe means all logic is atomic is the classic mistake. Only specific operations are atomic.

Writing get followed by put for the same key creates races. Replace those sequences with compute, merge, or putIfAbsent.

Ignoring the thread safety of stored values leads to subtle bugs. A safe map can still hold unsafe objects.

Doing blocking or heavy work inside compute functions can hurt concurrency. Keep mapping functions short and predictable.

Expecting iteration to be a perfect snapshot leads to wrong conclusions in debugging and metrics code.

Summary

  • 'ConcurrentHashMap provides atomicity for specific built-in operations, not arbitrary sequences.'
  • 'putIfAbsent, computeIfAbsent, compute, and merge are the usual tools for safe compound updates.'
  • Iteration is weakly consistent, not a frozen snapshot.
  • Atomicity is usually per key, not across several keys.
  • Thread safety of the map does not automatically make the stored values thread-safe.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.