Hashmap vs Concurrent Hashmap in Java
Hashmap
Hashmap is a Hash table based implementation of the Map interface. Hashmap provides all of the optional map operations and permits null values and the null key.
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
This class makes no guarantees as to the order of the map, in particular, it does not guarantee that the order will remain constant over time.
ConcurrentHashMap
A hash table supporting full concurrency of retrievals and high expected concurrency for updates.
ConcurrentHashMap class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.
All operations are thread-safe, retrieval operations. For retriaval there is no support for locking the entire table in a way that prevents all access.
In HashTables where every read/write operation needs to acquire the lock, there is no locking at the object level in ConcurrentHashMaps. It is thread safe without synchronizing the whole map.
ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it
Reads can happen very fast while write is done with a lock.
Uses
1). It can be used as scalable frequency map (a form of histogram or multiset) by using LongAdder values and initializing via computeIfAbsent.
2). You should use ConcurrentHashMap when you need very high concurrency in your aaplications like online trading,stock market.Banking sector.
Hashmap | Concurrent Hashmap | |
1. | HashMap is faster | ConcurrentHashMap is slower than HashMap. |
2. | HashMap is not synchronized.HashMap is not Thread-safe. | ConcurrentHashMap is synchronized.Hence ConcurrentHashMap is Thread-safe in nature |
3. | HashMap allows key and value to be null | ConcurrentHashMap does not allow null key/value. It will throw NullPointerException. |
4. | HashMap iterator is fail-fast and ArrayList throws ConcurrentModificationException if concurrent modification happens during iteration. | ConcurrentHashMap is fail-safe and it will never throw ConcurrentModificationException during iteration. |
5. | It is introduced in 1.2 Version of java | It is introduced in 1.5 Version of java |
6. | HashMap which is non-synchronized by nature can be synchronized by applying a wrapper using synchronized Map | ConcurrentHashMap is designed for concurrency and improve performance. |
7. | While one thread is Iterating the HashMap object, if other thread tries to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException | In ConcurrentHashMap we won't get any exception while performing any modification at the time of Iteration. |
Java program to explain drawbacks of HashMap
package com.javacodestuffs.core.collection.hashmap;
import java.util.HashMap;
public class HashMapExample extends Thread {
static HashMap <Integer,String> hm = new HashMap <Integer,String> ();
public void run() {
try {
Thread.sleep(1000);
hm.put(11, "Abhijit");
}
catch(InterruptedException e) {
System.out.println("Child Thread will add element");
}
}
public static void main(String[] args) throws InterruptedException {
hm.put(12, "Anna");
hm.put(13, "Rajiv");
hm.put(14, "Vaman");
hm.put(14, "Rohini");
HashMapExample thread = new HashMapExample();
thread.start();
for (Object obj: hm.entrySet()) {
Object newObj = obj;
System.out.println(newObj);
Thread.sleep(1000);
}
System.out.println(hm);
}
}
output:
12=Anna
13=Rajiv
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
at java.util.HashMap$EntryIterator.next(HashMap.java:1471)
at java.util.HashMap$EntryIterator.next(HashMap.java:1469)
at com.javacodestuffs.core.collection.hashmap.HashMapExample.main(HashMapExample.java:34)
Using ConcurrentHashMap with synchronization
package com.javacodestuffs.core.collection.hashmap;
import java.util.HashMap;
import java.util.concurrent. * ;
public class ConcurrentHashMapExample extends Thread {
static ConcurrentHashMap <Integer,String> conmap = new ConcurrentHashMap <Integer,String> ();
public void run() {
conmap.put(16, "Abhijit");
try {
Thread.sleep(2000);
}
catch(InterruptedException e) {
System.out.println("Child Thread going to add element");
}
}
public static void main(String[] args) throws InterruptedException {
conmap.put(12, "Anna");
conmap.put(13, "Rajiv");
conmap.put(14, "Vaman");
conmap.put(15, "Rohini");
ConcurrentHashMapExample thread = new ConcurrentHashMapExample();
thread.start();
for (Object obj: conmap.entrySet()) {
Object newObj = obj;
System.out.println(newObj);
Thread.sleep(1000);
}
System.out.println(conmap);
}
}
output:
16=Abhijit
12=Anna
13=Rajiv
14=Vaman
15=Rohini
{16=Abhijit, 12=Anna, 13=Rajiv, 14=Vaman, 15=Rohini}
HasMap null test
package com.javacodestuffs.core.collection.hashmap;
import java.util.* ;
public class HashMapTest {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put(12, "Anna");
hm.put(13, "Rajiv");
hm.put(14, "Vaman");
hm.put(15, "Rohini");
hm.put(null, "Abhijit");
System.out.println(hm);
}
}
output:
{null=Abhijit, 12=Anna, 13=Rajiv, 14=Vaman, 15=Rohini}
ConcurrentHashMap null test
package com.javacodestuffs.core.collection.hashmap;
import java.util.concurrent.* ;
public class ConcurrentHashMapDemo {
public static void main(String[] args) {
ConcurrentHashMap chm = new ConcurrentHashMap();
chm.put(12, "Anna");
chm.put(13, "Rajiv");
chm.put(14, "Vaman");
chm.put(15, "Rohini");
chm.put(null, "Abhijit");
System.out.println(chm);
}
}
output:
Exception in thread "main" java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
at java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
at com.javacodestuffs.core.collection.hashmap.ConcurrentHashMapDemo.main(ConcurrentHashMapDemo.java:14)
Why need ConcurrentHashMap and CopyOnWriteArrayList
The synchronized collections classes, Hashtable, and Vector, and the synchronized wrapper classes, Collections.synchronizedMap() and Collections.synchronizedList(), provide a basic conditionally thread-safe implementation of Map and List.
But some times ,it is not good to make use of them unsuitable for use in highly concurrent applications, for example, their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationException.
ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety.
CopyOnWriteArrayListExample
package com.javacodestuffs.core.collection.hashmap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample {
public static void main(String[] args) {
List<String> nameList = new ArrayList<>();
nameList.add("Anna");
nameList.add("Rajiv");
nameList.add("Vaman");
nameList.add("Rohini");
nameList.add("Abhijit");
Iterator<String> iterator = nameList.iterator();
System.out.println(nameList);
while (iterator.hasNext()) {
if (iterator.next().equals("Abhijit")) {
//removal is allowed.
iterator.remove();
}
}
System.out.println(nameList);
List <String>copyOnWriteArrayList = new CopyOnWriteArrayList <>();
copyOnWriteArrayList.add("Anna");
copyOnWriteArrayList.add("Rajiv");
copyOnWriteArrayList.add("Vaman");
copyOnWriteArrayList.add("Rohini");
copyOnWriteArrayList.add("Abhijit");
Iterator <String> iterator1 = copyOnWriteArrayList.iterator();
System.out.println(copyOnWriteArrayList);
while (iterator1.hasNext()) {
if (iterator1.next().equals("Abhijit")) {
try {
iterator1.remove();
} catch(UnsupportedOperationException e) {
System.out.println("Removal not allowed.");
}
}
}
System.out.println(copyOnWriteArrayList);
}
}
output:
[Anna, Rajiv, Vaman, Rohini, Abhijit]
[Anna, Rajiv, Vaman, Rohini]
[Anna, Rajiv, Vaman, Rohini, Abhijit]
Removal not allowed.
[Anna, Rajiv, Vaman, Rohini, Abhijit]
What happens when we iterate over concurrent HashMap and Hashmap?
Is ConcurrentHashMap slower than HashMap?
How do you make a HashMap concurrent?
Can we use HashMap in a multithreaded environment?
Where is HashMap used in real-time?
Why is HashMap unsynchronized?
The difference between HashMap and LinkedHashMap in Java?
The difference between Hashtable and HashMap in Java?
The difference between HashSet and TreeSet in Java?
Which is faster HashMap or TreeMap?
Which is faster HashMap or ArrayList?
The difference between TreeMap and TreeSet in Java?
The difference between HashMap and ConcurrentHashMap in Java?
Difference between ArrayList and HashSet in Java?
The difference between ArrayList and LinkedList in Java?
The difference between Vector and ArrayList in Java?
Difference between EnumMap and HashMap in Java
In this tutorial, we have seen the Hashmap vs Concurrent Hashmap in Java with examples. All source code in the tutorial can be found in the GitHub repository.
0 Comments
Post a Comment