Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashmap in multithreaded environment when doing resizing

Tags:

java

hashmap

I am following a tutorial and it basically explains about the cause of race condition which happens when resizing Hashmap in a multithreaded environment:

In Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during their migration to new bucket because java HashMap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop

I have two questions after reading this:

  1. Why is the linked list for each bucket be reversed in order?
  2. I can see there could be race condition, but cannot see how the infinite loop comes? Is it because one thread might append the element head to tail while the other doing it in the reverse order?

Please help me to clarify this, much appreciated!

like image 953
Kevin Avatar asked Apr 12 '13 14:04

Kevin


1 Answers

The answer for your first question is in the quoted text:

"because java HashMap doesn't append the new element at tail instead it append new element at head to avoid tail traversing"

If HashMap would store them in insertion order it had to traverse the list at each insertion or store an extra pointer to the end of the list (and maintain it). Anyhow storing the elements in the bucket in insertion order would not give any benefits (at least I can't think of any).

The answer to your second question relies here:

http://mailinator.blogspot.hu/2009/06/beautiful-race-condition.html

like image 162
Nándor Krácser Avatar answered Oct 06 '22 16:10

Nándor Krácser