Multithreading: ConcurrentHashMap.putIfAbsent inserts atomically

putIfAbsent checks for a key and inserts in one atomic step, so no other thread can sneak a write in between the check and the insert the way a separate containsKey/put pair would allow. It returns the previous value, or null when its own insert won.

Code
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("a", 1);
Integer previousA = map.putIfAbsent("a", 99);
Integer previousB = map.putIfAbsent("b", 2);
System.out.println("Existing key kept: " + map.get("a") + ", old value returned: " + previousA);
System.out.println("New key inserted: " + map.get("b") + ", returned: " + previousB);
Output
Existing key kept: 1, old value returned: 1
New key inserted: 2, returned: null
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms