• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multiple threads and HashMap

 
Rama Kundurthi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I am troubleshooting thread deadlock scenario with HashMap. When multiple threads are trying to add to a hashmap at the same time, is it possible to have a race condition?. This HashMap is simple hashmap and it is not thread safe one. If answer is yes, where can I get more information on this. As such at the moment, I am not worried about data inconsistencies.

Thanks
 
Henry Wong
author
Marshal
Pie
Posts: 21518
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't be trying to figure out the limits of the damage, either it is thread safe or it isn't. Using a collection that is not thread safe with multiple threads because you are will to accept certain data inconsistencies is not a good idea.

However, in this case, the HashMap class does document the extent that you are allowed to maintain safety. The class is thread safe as long as you don't change the structure of the class -- meaning that you are even allowed to call add() provided that the operation winds up replacing an object in the hashmap.

Henry
 
Rama Kundurthi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry.

Thats what I thought (-- meaning that you are even allowed to call add() provided that the operation winds up replacing an object in the hashmap). But it seems jvm is hanging in linux environment. When I made the class as thread safe, every thing seems to be fine and no deadlock issue.

PS: I was trouble shooting a code that I am inherited with. Before fixing, I needed to know this is the exact problem (to confirm that my fix works)
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given that HashMap doesn't use synchronized methods, the danger of having multiple threads access one instance simultaneously won't be deadlock (both threads waiting for a lock on an object the other thread is already holding) but NPE or possibly an infinite loop. If it looks like deadlock, it's probably an infinite loop.

The end result is the same, however: you need to guard your multithreaded usage of HashMap unless you can prove your method calls are safe in all scenarios. There's also ConcurrentHashMap if you're so lucky as to be working on JDK 1.5.
[ February 07, 2005: Message edited by: David Harkness ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic