Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnâ€™t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isnâ€™t.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object â€śstructurallyâ€ť, a concurrent modification exception will be thrown. It is possible for other threads though to invoke â€śsetâ€ť method since it doesnâ€™t modify the collection â€śstructurallyâ€ť. However, if prior to calling â€śsetâ€ť, the collection has been modified structurally, â€śIllegalArgumentExceptionâ€ť will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);