Sunday, November 20, 2011

Synchronizing a HashMap


How to make hashmap operations synchronized?

For JDK 5 or after, we can use ConcurrentHashMap . This is an efficient implementation of a concurrent hash map using different locks for different portions of the HashMap . This reduces the contention of the lock and hence increase throughput tremendously as compared to a synchronized Map.

For JDK versions before JDK5 there is a back port of the same, if we do not want to use that, then we can use Collections.synchronizedMap() method to create a synchronized map. The new map will be backed with the original map and all the access will be synchronized on a single monitor. Also, we have to do external synchronization while iterating over the map entries.

Stumble
Delicious
Technorati
Twitter

0 Comments:

Post a Comment