Junior — Middle
How can you ensure atomic addition of data in HashMap under multithreading conditions?
sobes.tech AI
Answer from AI
In multithreading conditions, the standard HashMap in Java is not thread-safe, so for atomic data addition, special approaches should be used:
-
Use
ConcurrentHashMap— a thread-safe implementation of Map that allows safe addition and modification of data from multiple threads. -
Method
putIfAbsent— atomically adds a value if the key is absent:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.putIfAbsent("key", 1);
- Use methods
compute,computeIfAbsentfor atomic update operations:
map.compute("key", (k, v) -> (v == null) ? 1 : v + 1);
If a regular HashMap is used, access must be synchronized manually, for example, via Collections.synchronizedMap or synchronized blocks, but this is less efficient.
In summary, for atomic data addition in a multithreaded environment, it is better to use ConcurrentHashMap with its atomic methods.