Create Thread-safe HashMap Without Using Collections.synchronizedMap in Java
Last Updated :
31 Jan, 2024
The HashMap class in Java is a commonly used data structure for storing key-value pairs. While HashMap provides fast and efficient operations, it is not inherently thread-safe. When working in a multi-threaded environment, it's crucial to ensure that data structures are accessed and modified in a way that prevents race conditions and maintains consistency.
In this article, we will learn How to create a thread-safe HashMap without using Collections.synchronizedMap in Java.
Thread-Safe HashMap Without Using Collections.synchronizedMap in Java
One commonly used approach to achieving thread safety with a HashMap is to use the Collections.synchronizedMap method. However, there's an alternative method to create a thread-safe HashMap without relying on this utility.
The Challenge of Thread Safety: In a multi-threaded environment, simultaneous access to a non-thread-safe HashMap can lead to data corruption and unpredictable behavior. To address this, developers often synchronize access to the HashMap using techniques such as Collections.synchronizedMap or manual synchronization with synchronized blocks.
1. Using ConcurrentHashMap - An Alternative
An alternative to explicit synchronization is to use the ConcurrentHashMap class, introduced in Java 5. ConcurrentHashMap is specifically designed for concurrent access and provides better performance in comparison to synchronized maps.
Here's an example of how you can create and use a thread-safe HashMap using ConcurrentHashMap:
Java
// Java program demonstrating the use of
// ConcurrentHashMap for thread-safe operations
import java.util.concurrent.ConcurrentHashMap;
// Class definition
public class ThreadSafeHashMapExample {
// Main method
public static void main(String[] args)
{
// Creating a thread-safe HashMap
// without using Collections.synchronizedMap
ConcurrentHashMap<String, Integer> threadSafeMap = new ConcurrentHashMap<>();
// Adding key-value pairs to the ConcurrentHashMap
threadSafeMap.put("One", 1);
threadSafeMap.put("Two", 2);
threadSafeMap.put("Three", 3);
// Accessing and printing values using forEach and a
// lambda expression
threadSafeMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
Output:
One: 1
Two: 2
Three: 3
In this example, the ConcurrentHashMap is used instead of a regular HashMap. The operations on this map are inherently thread-safe, eliminating the need for external synchronization.
2. Implementing Custom Thread-Safe HashMap
If you want to create a thread-safe HashMap without using ConcurrentHashMap, you can implement your own custom solution. One approach is to use locks to synchronize critical sections of code:
Java
// Java program demonstrating a custom
// thread-safe HashMap using explicit locks
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
// CustomThreadSafeHashMap with generic
// key (K) and value (V) types
public class CustomThreadSafeHashMap<K, V> {
// Private instance variables
private final Map<K, V> map = new HashMap<>();
private final Lock lock = new ReentrantLock();
// Method to add a key-value pair
// to the map in a thread-safe manner
public void put(K key, V value) {
// Acquiring the lock
lock.lock();
try {
// Performing the put operation on the map
map.put(key, value);
} finally {
// Releasing the lock in a finally block
// to ensure it happens even if an exception occurs
lock.unlock();
}
}
// Method to retrieve a value associated
// with a key in a thread-safe manner
public V get(K key) {
// Acquiring the lock
lock.lock();
try {
// Performing the get operation on the map
return map.get(key);
} finally {
// Releasing the lock in a finally block
// to ensure it happens even if an exception occurs
lock.unlock();
}
}
// Main method for testing the CustomThreadSafeHashMap
public static void main(String[] args) {
// Creating an instance of CustomThreadSafeHashMap
// with String keys and Integer values
CustomThreadSafeHashMap<String, Integer> customThreadSafeMap = new CustomThreadSafeHashMap<>();
// Adding key-value pairs to the custom thread-safe map
customThreadSafeMap.put("One", 1);
customThreadSafeMap.put("Two", 2);
customThreadSafeMap.put("Three", 3);
// Accessing and printing values associated with specific keys
System.out.println("Value for key 'One': " + customThreadSafeMap.get("One"));
System.out.println("Value for key 'Two': " + customThreadSafeMap.get("Two"));
System.out.println("Value for key 'Three': " + customThreadSafeMap.get("Three"));
}
}
Output:
Value for key 'One': 1
Value for key 'Two': 2
Value for key 'Three': 3
In this example, a ReentrantLock is used to synchronize access to the HashMap. Each critical section of code is enclosed within lock and unlock calls, ensuring that only one thread can access the map at a time.
Similar Reads
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 = Coll
3 min read
Collections unmodifiableMap() method in Java with Examples
The unmodifiableMap() method of java.util.Collections class is used to return an unmodifiable view of the specified map. This method allows modules to provide users with "read-only" access to internal maps. Query operations on the returned map "read through" to the specified map, and attempts to mod
2 min read
Collections unmodifiableSortedMap() method in Java with Examples
The unmodifiableSortedMap() method of java.util.Collections class is used to return an unmodifiable view of the specified sorted map. This method allows modules to provide users with "read-only" access to internal sorted maps. Query operations on the returned sorted map "read through" to the specifi
2 min read
How to Convert a HashTable to Other Collections Types in Java?
In Java, a Hashtable is a data structure that stores the data in the form of key and value pairs. And each key is mapped to a specific value. It implements the Map interface. HashTable provides a simple way to access the data using the unique keys. In this article, we will learn how to convert a Has
3 min read
Getting Synchronized Map from Java HashMap
HashMap is a non synchronized collection class. If we want to perform thread-safe operations on it then we must have to synchronize it explicitly. In order to synchronize it explicitly the synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map back
2 min read
Getting Synchronized Set from Java TreeSet
In java.util.Collections class, synchronizedSet() method is used to return a synchronized (thread-safe) set backed by the specified set. This method takes the TreeSet as a parameter. To guarantee serial access, it is critical that all access to the backing set is accomplished through the returned se
2 min read
Convert String or String Array to HashMap In Java
Considering a string object that contains the student name and roll number separated by a comma, and each student contains the name and roll number separated by a colon. Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name be
4 min read
Collections unmodifiableCollection() method in Java with Examples
The unmodifiableCollection() method of java.util.Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with "read-only" access to internal collections. Query operations on the returned collection "read through" to the specif
2 min read
How to Synchronize HashMap in Java?
HashMap is part of the Collection's framework of java. It stores the data in the form of key-value pairs. These values of the HashMap can be accessed by using their respective keys. The key-value pairs can be accessed using their indexes (of Integer type). HashMap is similar to HashTable in java. Th
2 min read
How does HashMap handle resizing when it reaches its capacity in Java?
The capacity of a HashMap simply doubles when it reaches a certain threshold. The threshold depends on the initial capacity and the load factor of the HashMap. Consider Capacity as the number of spaces, a HashMap currently has to store elements and Load factor is a measure of how full the map is all
3 min read