HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
In Core Java, you can make a HashMap
synchronized by using the Collections.synchronizedMap()
method. This method returns a synchronized (thread-safe) map backed by the specified map. Here’s an example:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SynchronizedHashMapExample {public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> hashMap = new HashMap<>();
// Populating the HashMap
hashMap.put(“One”, 1);
hashMap.put(“Two”, 2);
hashMap.put(“Three”, 3);
// Making the HashMap synchronized
Map<String, Integer> synchronizedMap = Collections.synchronizedMap(hashMap);
// Now, ‘synchronizedMap’ can be safely used in a multi-threaded environment
}
}
By wrapping the original HashMap
using Collections.synchronizedMap()
, you obtain a synchronized map that ensures thread safety during concurrent access. Keep in mind that while this approach provides basic synchronization, it might not be as efficient as other concurrent data structures available in the java.util.concurrent
package, like ConcurrentHashMap
, for more advanced concurrency scenarios.