Open In App

How to Create a Synchronized HashTable in Java?

In Java, a synchronized HashTable is achieved by wrapping a regular HashTable with the Collection.synchronizedMap( ) method. This wrapper ensures that each method of the Map interface is synchronized, making the HashTable thread-safe.

Syntax:

Map<KeyType, ValueType> synchronizedHashTable = Collections.synchronizedMap(new HashTable<>());

Parameters:

Approaches:

Program to Create a Synchronized HashTable in Java

Below are the code implementations using the above two approaches.



Approach 1: Using Collections.synchronizedMap()

Below is the Program to create a synchronized HashTable using Collections.synchronizedMap().




// Java program to Create a synchronized HashTable
// Using Collections.synchronizedMap( )
import java.io.*;
import java.util.*;
  
class SynchronizedHashTable {
    public static void main (String[] args) {
      // Create a hash table
      Map<String, Integer> hashTable = new HashMap();
        
      // Wrap the hash table with a synchronized map
      Map<String, Integer> synchronizedHashTable = Collections.synchronizedMap(hashTable);
        
      // Perform operations on the synchronized hash table
      synchronizedHashTable.put("one", 1);
      synchronizedHashTable.put("Two", 2);
      synchronizedHashTable.put("Three",3);
        
      // Iterate over the synchronized hash table
      synchronized (synchronizedHashTable) {
        for (Map.Entry<String, Integer> entry : synchronizedHashTable.entrySet()) {
            
        System.out.println("Synchronized HashTable is: " + entry.getKey() + ": " + entry.getValue());
       }
     }
  }
}

Output

Synchronized HashTable is: one: 1
Synchronized HashTable is: Two: 2
Synchronized HashTable is: Three: 3

Explanation of the above Program:

Approach 2: Using Concurrent Class

Below is the Program to Create a Synchronized HashTable using Concurrent Class




// Java program to create a synchronized HashTable
// Using concurrent class
import java.util.*;
import java.util.concurrent.*;
   
public class ConcurrentHashTable {
    public static void main(String[] args) {
        // Create a concurrent Hash Table
        ConcurrentHashMap<String, Integer> concurrentHashTable = new ConcurrentHashMap<>();
   
        // Perform operations on the concurrent Hash Table
        concurrentHashTable.put("one", 1);
        concurrentHashTable.put("two", 2);
        concurrentHashTable.put("three", 3);
   
        // Iterate over the concurrent hash table
        for (Map.Entry<String, Integer> entry : concurrentHashTable.entrySet()) {
            System.out.println("Synchronized HashTable is: " + entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output
Synchronized HashTable is: one: 1
Synchronized HashTable is: two: 2
Synchronized HashTable is: three: 3

Explanation of the above Program:


Article Tags :