Saturday, April 13, 2019

Java Collection API - ConcurrentHashMap in Java

ConcurrentHashMap

ConcurrentHashMap extends AbstractMap and implements ConcurrentMap interface.

Features of ConcurrentHashMap

  • ConcurrentHashMap in java is similar to HashMap except Thread - safety.
  • Null key is not allowed in ConcurrentHashMap
  • Thread-Safety in ConcurrentHashMap is achieved by separate lock for each separate buckets.
  • Similar to HashMap, ConcurrentHashMap have default capacity of 16 buckets and concurrency level is also 16 because each buckets have its own lock so that 16 thread work concurrently.
  • Iterator provided by ConcurrentHashMap is Fail-Safe while HashMap iterator is Fail-Fast, which means that it will not throw ConcurrentModificationException.
  • Read operations  don't block whole Map, So may overlap with update operation(including put and remove).

Why another Map required?, While we have Collections.synchronizedMap() method for making any Map Thread-Safe.

Problem with Hashtable or Synchronized Map is that 
1. All the methods are synchronized with common lock thus only single thread can access at a time,
2.  even for a read operation.

ConcurrentHashMap  solve this issue, so that ConcurrentHashMap provide better performance. 

How the performance is improved in ConcurrentHashMap

1. Solved First issue
ConcurrentHashMap is like the HashMap except one difference that its locking strategy for thread saftey. Unlike Hashtable and synchronized Map , it does not synchronized every method on common lock. ConcurrentHashMap uses separate lock for separate buckets thus locking only portion of Map.

When you construct an HashMap using no-args constructor, internally it create  16 buckets. ConcurrentHashMap also create by default 16 buckets but all 16 buckets have separate locks. So default Concurrency level of ConcurrentHashMap is 16. Since there are by default 16 buckets having 16 separate locks which means 16 threads operates concurrently.

So you can see ConcurrentHashMap provide better performance by locking only portion of the map rather than locking whole map at a time for a single operation, resulting greater performance.

2. Solved 2nd issue
Performance of Java ConcurrentHashMap  is further improved by providing read access concurrently without any blocking.

Constructor in ConcurrentHashMap

  • ConcurrentHashMap() - Construct an empty ConcurrentHashMap() with default capacity of 16 and default load factor of 0.75
  • ConcurrentHashMap(int Capacity) - Construct an empty ConcurrentHashMap with provided capacity and default load factor
  • ConcurrentHashMap(int capacity, double loadFactor) - Construct an empty ConcurrentHashMap with provide capacity and loadFactor.
  • ConcurrentHashMap(Map<? extends K, ? extends V> map) -construct a ConcurrentHashMap using provided map.

Java ConcurrentHashMap Example

Null key not allowed

Fail-Safe itrator


When is ConcurrentHashMap a better choice

ConcurrentHashMap is a better choice when there are more reads than writes. As mentioned above retrieval operations are non-blocking so many concurrent threads can read without any performance problem. If there are more writes and that too many threads operating on the same segment then the threads will block which will deteriorate the performance.

Difference between ConcurrentHashMap and HashMap

It is good interview Question. ConcurrentHashMap was added in Java 5 and its implementation is modified in Java 8. 
1. Thread-Safety - First Difference is Thread - Safety, ConcurrentHashMap is design for Multi-Threaded environment. While we can make HashMap also Thread - Safe using Collections.synchronizedMap(HashMap map) method but it reduce the performance because Collections.synchronizedMap(HashMap map) method synchronized all the methods hence at a time only one thread can access a Map. While in ConcurrentHashMap Multiple Thread can perform operation. 
2. Locking Concept - 
3. allowed non blocking read access for performance improvement
4. ConcurrentHashMap does not allowed null key while HashMap allowed one and only one null key.
5. Iterator of HashMap is Fail-Fast while ConcurrentHashMap Iterator is Fail-Safe. i.e. After getting iterator if map is modified it will not throw ConcurrentModificationException.



Question and Answer

Q: So Mr.Hash Map, how can I find if a particular key has been assigned to you?

A: Cool, you can use the containsKey(Object KEY) method with me, it will return a Boolean value if I have a value for the given key.

Q: How do I find all the available keys that are present on the Map?

A: I have a method called as keyset() that will return all the keys on the map. In the above example, if you write a line as – System.out.println(objMap.keySet());

It will return an output as-
[Name, Type, Power, Price]

Similarly, if you need all the values only, I have a method of values().
System.out.println(objMap.values());

It will return an output as-
[Suzuki, 2-wheeler, 220, 85000]

Q: Suppose, I need to remove only a particular key from the Map, do I need to delete the entire Map?

A: No buddy!! I have a method of remove(Object KEY) that will remove only that particular key-value pair.

Q: How can we check if you actually contain some key-value pairs?

A: Just check if I am empty or not!! In short, use isEmpty() method against me ;) 

No comments:

Post a Comment