This question already has an answer here:
What is the difference between a ConcurrentHashMap and a Hashtable in Java?
Which is more efficient for threaded applications?
ConcurrentHashMap uses multiple buckets to store data. This avoids read locks and greatly improves performance over a HashTable. Both are thread safe, but there are obvious performance wins with ConcurrentHashMap.
When you read from a ConcurrentHashMap using get(), there are no locks, contrary to the HashTable for which all operations are simply synchronized.
HashTable was released in old versions of Java whereas ConcurrentHashMap is a java 5+ thing.
HashMap is the best thing to use in a single threaded application.
ConcurrentHashMap and Hashtable locking mechanism
Hashtableis belongs to the Collection framework;ConcurrentHashMapbelongs to the Executor framework.Hashtableuses single lock for whole data.ConcurrentHashMapuses multiple locks on segment level (16 by default) instead of object level i.e. wholeMap.ConcurrentHashMaplocking is applied only for updates. In case of retrievals, it allows full concurrency, retrievals reflect the results of the most recently completed update operations. So reads can happen very fast while writes are done with a lock.ConcurrentHashMapdoesn't throw aConcurrentModificationExceptionif one thread tries to modify it while another is iterating over it and does not allow null values.ConcurrentHashMapreturnsIterator, which fails-safe (i.e. iterator will make a copy of the internal data structure) on concurrent modification.ConcurrentHashMapuses a database shards logic (Segment<K, V>[] segments) is known as Concurrency-Level, i.e. divides the data into shards(segments) than puts locks on each shard (segment) instead of putting a single lock for whole data (Map). The default value is 16.
To understand the ConcurrentHashMap more technically please look at this link
The following analogy helps you get understand the concept only(not logic)
- Assume
HashtableandConcurrentHashMapare two types of Homes. Hashtablelocks home's main door.ConcurrentHashMaplocks specific room door instead of main door.
Which is more efficient for threaded applications?
ConcurrentHashMap is more efficient for threaded applications.
来源:https://stackoverflow.com/questions/12646404/concurrenthashmap-and-hashtable-in-java