I was going through an interview question on JavaRevisited and I’m having difficulty understanding this question :
What’s wrong with using a HashMap in a multithreaded environment? When get() method go into an infinite loop?
In my opinion, it’s not a problem to use HashMap inside a multi-threaded environment, as long as our application is not accessing/reading threads which are modifying the created HashMap, rather than simply accessing the HashMap.
So, as I see it, there’s not a problem as long as in the application we are just accessing the HashMap in a multi-threaded environment.
Please let me know if my understanding is correct.
It is a bug to have multiple threads use a non-synchronized collection (really any mutable class) in an unprotected manner. Certain if each thread had their own
HashMapinstance then this is not an issue. It is a problem if multiple threads are adding to the sameHashMapinstance without it beingsynchronized. Even if just 1 thread is modifying aHashMapand other threads are reading from that same map without synchronization, you will run into problems.If you need to use the same hash table object in multiple threads then you should consider using
ConcurrentHashMap, wrapping each of the accesses to theHashMapin asynchronized {}block, or making use of theCollections.synchronizedMap(new HashMap<...>())construct.Chances are that the
get()goes to an infinite loop because one of the threads has only a partially updated view of theHashMapin memory and there must be some sort of object reference loop. That’s the peril of using an unsynchronized collection with multiple threads.If by "accessing" you mean "reading", then this is true with qualifications. You must make sure:
HashMapare completed before the threads are instantiated and the thread that creates the map also forks the threadsHashMapin read-only mode – eitherget()or iteration without removeIf any of these conditions are not true then you will need to use a synchronized map instead.