HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.
This example shows how to make a HashMap Synchronized in Java using synchronizedMap method of the Collections class.
Iterator should be used in a synchronized block even if we have synchronized the HashMap explicitly.
1 2 3 4 5 6 7 8 9 10 11 12 |
Map map = Collections.synchronizedMap(new HashMap()); ... // This doesn't need to be in synchronized block Set set = map.keySet(); // Synchronizing on map, not on set synchronized (map) { // Iterator must be in synchronized block Iterator iterator = set.iterator(); while (iterator.hasNext()) { ... } } |