Difference between HashTable and ConcurrentHashMap in Java

JavaObject Oriented ProgrammingProgramming

Concurrent Hashmap is a class that was introduced in jdk1.5.  Concurrent hash map applies locks only at bucket level called fragment while adding or updating the map. So, a concurrent hash map allows concurrent read and write operations to the map. 

HashTable is a thread-safe legacy class introduced in the Jdk1.1. It is a base implementation of Map interface. It doesn't allow null keys and values. It is synchronized in nature so two different threads can’t access simultaneously. Hashtable does not maintain any order.

Sr. No.
Key
HashTable
ConcurrentHashMap

1

Basic 

HashTable is a thread-safe legacy class introduced in the Jdk1.1

 ConcurrentHashmap is a class that was introduced in jdk1.5

2

Locking

It applies lock on the entire collection 

ConcurrentHashMap apply locks only at bucket level called fragment  while adding or updating the map

3

Performance 

It is slower than  ConcurrentHashMap

It is better than HashTable

4.

Null

It doesn't allow null key and value

It allows null key and value

Example of Hashtable

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
public class HashtableExample {
   public static void main(String[] args) {
      // create Hashtable
      Hashtable map = new Hashtable();
      map.put("HCL", "100");
      map.put("DELL", "200");
      map.put("IBM", "300");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}

Example of ConcurrentHashMap

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
   public static void main(String[] args) {
      // ConcurrentHashMap
      Map myMap = new ConcurrentHashMap();
      myMap.put("HCL", "1");
      myMap.put("DELL", "1");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}
raja
Published on 21-Jan-2020 08:14:07
Advertisements