Java - Difference between ConcurrentHashMap, Hashtable and Synchronized Map

来源:互联网 发布:中控网络指纹考勤机 编辑:程序博客网 时间:2024/05/24 05:13

http://javarevisited.blogspot.de/2011/04/difference-between-concurrenthashmap.html

Because sometimes I can't open this page without proper proxy configuration, so I have to copy some content here.


Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is significant difference between them, which arise from the fact that how they achieve their thread-safety.     

Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread-safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if number of thread increases.

Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. Only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method.

ConcurrentHashMap is especially designed for concurrent use i.e. more than one thread. By default it simultaneously allows 16 threads to read and write from Map without any external synchronization. It is also very scalable because of stripped locking technique used in internal implementation of ConcurrentHashMap class. Unlike Hashtable and Synchronized Map, it never locks whole Map, instead it divides the map in segments and locking is done on those. It perform better if number of reader threads is greater than number of writer threads.

In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.
ConcurrentHashMap do not allow null keys or null values while synchronized HashMap allows one null keys.


0 0
原创粉丝点击