Lets
try to understand the problem in HashTable, whenever you tries to
perform insertion, removal, traversal operations on HashTable, a
thread must acquire lock on
entire map. This
prevents other threads from accessing the Map
at
all while the lock is held, even if idle processors are available,
which is limiting concurrency.
ConcurrentHashMap solves this problem by maintaining 32 locks, where each lock guards a subset of hash buckets. Since there are 32 separate locks guarding hashmap, so at max 32 threads can able to perform operations on HashMap at a time, means if you want to insert an element to ConcurrentHashMap, you are getting lock on subset of hash buckets (Where this element should go), not on entire map.
ConcurrentHashMap solves this problem by maintaining 32 locks, where each lock guards a subset of hash buckets. Since there are 32 separate locks guarding hashmap, so at max 32 threads can able to perform operations on HashMap at a time, means if you want to insert an element to ConcurrentHashMap, you are getting lock on subset of hash buckets (Where this element should go), not on entire map.
import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapEx { public static void main(String args[]){ ConcurrentHashMap<Integer, String> map; map = new ConcurrentHashMap<> (); map.put(111, "Krishna"); map.put(12, "Arjun"); map.put(93, "Abdul"); map.put(4, "jaideep"); System.out.println(map); } }
Output
{4=jaideep, 12=Arjun, 93=Abdul, 111=Krishna}
No comments:
Post a Comment