A thread-safe HashMap can be implemented by synchronizing access to a standard HashMap so that only one thread can perform read or write operations at a time. This prevents race conditions and data corruption when multiple threads access the map concurrently. A common approach is to use Collections.synchronizedMap() or explicit synchronization blocks around map operations.
Key Points: • Collections.synchronizedMap() wraps a HashMap and synchronizes all access to the underlying map. • When iterating over a synchronized map, external synchronization is still required to avoid inconsistent results. • This approach is simple but may reduce scalability because all operations use a single lock, creating contention under heavy load.
Example: In an application that stores user sessions in a shared map, multiple threads may add, update, or retrieve session data simultaneously. Wrapping the HashMap with synchronization ensures that only one thread modifies the map at a time, maintaining data consistency.
Code Example:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SessionStore {
private final Map<String, String> sessions =
Collections.synchronizedMap(
new HashMap<>());
public void addSession(String id,
String user) {
sessions.put(id, user);
}
public String getSession(
String id) {
return sessions.get(id);
}
}Interview Tip: A concise interview answer is: Without using ConcurrentHashMap, I can make a HashMap thread-safe by wrapping it with Collections.synchronizedMap() or by using synchronized blocks around map operations. This ensures thread safety, although it may impact performance because all threads must compete for the same lock.