Hashtable is a legacy class before Java Collections Framewpork (JCF) was introduced. The synchronized methods of Hashtable obtain lock on the entire hashtable object during any retrieval or update operations. This can lead to increased response time under heavy load and impacts performance.
A better alternative?
Java SE 5 introduced ConcurrentHashMap, a map implementation which provides better concurrency and scalability as compared to Hashtable. Since the underlying data is stored in a series of buckets in a hashmap (note that a hashtable is also a hashmap implementation), it would be more efficient to lock only a bucket while accessing a map instead of obtaining lock on the entire map.
In other words, ConcurrentHashMap uses this mechanism which provides multiple bucket locks and reduces lock contention when multiple threads access a ConcurrentHashMap object concurrently. This improves performance over a Hashtable, especially in a highly concurrent system.
Multiple internal buckets of ConcurrentHashMap |
Simple Benchmark (in milliseconds)
Hashtable
Cache put (100,000 objects): 626.8
Cache get (100,000 objects): 0.45
Cache put (500,000 objects): 3,544.6
Cache get (500,000 objects): 0.47
ConcurrentHashMap
Cache put (100,000 objects): 501.2
Cache get (100,000 objects): 0.22
Cache put (500,000 objects): 3,159
Cache get (500,000 objects): 0.24
Summary
In summary, both classes are thread-safe. In terms of performance, ConcurrentHashMap also performs better than HashTable with improvements in object put/get in/from cache. Developers should consider replacing usage of Hashtable with ConcurrentHashMaps in projects to improve performance and efficiency.
No comments:
Post a Comment