Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can multiple threads corrupt internal structure of Hashmap

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?

like image 553
Kshitiz Sharma Avatar asked May 06 '14 06:05

Kshitiz Sharma


People also ask

Why HashMap should not be used for multi threaded environments?

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.

Can multiple threads access HashMap?

— 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.

What will happen if multiple threads accessing the same resource?

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.


1 Answers

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!

like image 162
geoand Avatar answered Sep 19 '22 01:09

geoand