In Java 8 for the Really Impatient
Horstmann writes:
If multiple threads modify a plain HashMap, they can destroy the internal structure. Some of the links may go missing, or even go in circles, rendering the data structure unusable. (Section 6.2.1)
I can understand that unsynchronized concurrent access can corrupt my data. If both two threads update same value one can overwrite the other.
But why and how would it corrupt the internal memory structure?
It is a problem if multiple threads are adding to the same HashMap instance without it being synchronized . Even if just 1 thread is modifying a HashMap and other threads are reading from that same map without synchronization, you will run into problems.
— Hashmap can solve performance issue by giving parallel access to multiple threads reading hashmap simultaneously. But Hashmap is not thread safe, so what will happen if one thread tries to put data and requires Rehashing and at same time other thread tries to read data from Hashmap, It will go in infinite loop.
Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.
The answer you are seeking is perfectly explained in this blog post.
If you read through it you will see that a race condition can among other things corrupt the pointers between items in a bucket, thus causing a lookup to turn into an infinite traversal between two items.
I am not exactly sure how much the implementation of HashMap
has changed for Java 8, but I suspect that the basics still apply.
I should also add that this problem is not too difficult to encounter, I have actually seen it happen in a real life production system!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With