Junior — Middle
How is safe usage of HashMap implemented in multithreading conditions?
sobes.tech AI
Answer from AI
To safely use HashMap in a multithreaded environment, several approaches can be applied:
-
Use
Collections.synchronizedMap(new HashMap<>())— returns a synchronized wrapper around HashMap, where all methods are blocked to ensure thread safety. -
Use
ConcurrentHashMap— a specialized Map implementation optimized for concurrent access without full locking. -
Manually synchronize access to HashMap using the
synchronizedkeyword or other synchronization mechanisms.
Example of using ConcurrentHashMap:
import java.util.concurrent.ConcurrentHashMap;
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
Integer value = map.get("key1");
This class provides high performance when multiple threads access it simultaneously without the risk of race conditions.