This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
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.
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)
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 ]