Is a HashMap thread-safe for different keys?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
HashMaps are a popular data structure in Java, often used for their efficient data retrieval capabilities. However, when it comes to multi-threaded applications, understanding the thread-safety of a `HashMap` is crucial. This article explores whether `HashMap` is thread-safe when accessing different keys, discusses various scenarios where concurrent modifications might occur, and examines alternatives that guarantee thread safety.
Understanding Thread Safety in HashMaps
A `HashMap` in Java is not thread-safe. This means that if multiple threads access a `HashMap` concurrently and at least one of the threads modifies the map structurally (changes its size, such as by adding or removing elements), the map must be synchronized externally.
Structural Modifications
Structural modifications are those that change the map's size or potentially affect its internal data representation. These changes might affect existing entries and compromise data integrity when accessed by multiple threads simultaneously.
Accessing Different Keys
Many developers wonder if accessing different keys in a `HashMap` concurrently is safe, assuming that the keys hash to different buckets in the internal bucket array. While this assumption seems logical, it fails to address potential issues:
- Concurrent Structure Changes: If two threads are modifying the map (e.g., inserting or deleting entries), structural changes like rehashing can occur, affecting all keys, regardless of their individual hash codes.
- Internal `Hash` Algorithm: The insertion or deletion of one key might prompt adjustments like rehashing or resizing, which do not consider whether the affected buckets are different or the same. As these structures are altered, simultaneous operations from multiple threads can lead to exceptions or data inconsistency.
- Visibility of Changes: Even without structural modifications, the results of changes made by one thread might not be immediately visible to another thread due to Java Memory Model behaviors.
Example Scenario
To illustrate, consider a scenario where two threads perform operations on different keys:
- The readerThread might read null for keys not yet added or encounter concurrent modification errors.
- In extreme cases, the example may throw a `ConcurrentModificationException`.
Related reading
- Is a Java hashmap search really O1?
- Is a list potentially divisible by another?
- Is a Python dictionary an example of a hash table?
- Is a Python list guaranteed to have its elements stay in the order they are inserted in?
- Is armadillo solve thread safe?
- Is async await truly non-blocking in the browser?
- Is a Java string really immutable?
- Is asynchronous jdbc call possible?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.