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) 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 ([] segments Map). The default value is 16.
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.
Comments
Post a Comment