Atomic Operations: putIfAbsent, replace, remove with Value
You'll learn how to safely update a ConcurrentHashMap with single, thread-safe method calls that prevent race conditions.
The Problem with Check-Then-Act
In concurrent environments, a common mistake is splitting operations into separate steps:
// DANGEROUS in multi-threaded code:
if (!map.containsKey("user")) {
map.put("user", "Alice"); // Another thread might have inserted between check and put!
}
Between checking and acting, another thread could modify the map. This is called a race condition.
Atomic Methods to the Rescue
ConcurrentHashMap provides methods that perform check-and-update as a single atomic operation — indivisible and thread-safe without external synchronization.
putIfAbsent
Inserts a key-value pair only if the key is absent:
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.putIfAbsent("user", "Alice"); // Returns null, inserts "Alice"
map.putIfAbsent("user", "Bob"); // Returns "Alice", does NOT replace
Analogy: Like claiming a parking spot — if it's empty, you take it atomically; if occupied, you can't.
replace
Replaces a value only if the key exists:
map.put("status", "pending");
map.replace("status", "completed"); // Works, returns "pending"
map.replace("missing", "value"); // Does nothing, returns null
replace with Value Check
Replaces only if current value matches the expected value:
map.put("counter", "5");
map.replace("counter", "5", "6"); // Succeeds, returns true
map.replace("counter", "5", "7"); // Fails, returns false (value is now "6")
remove with Value
Removes only if the key maps to the specified value:
map.put("session", "abc123");
map.remove("session", "abc123"); // Succeeds, returns true
map.remove("session", "wrong"); // Fails, returns false
Key Takeaway: Use ConcurrentHashMap's atomic methods (putIfAbsent, replace, conditional remove) to perform thread-safe check-and-update operations without external locks or race conditions.