Using HashMap in multithreaded environment

java, multithreading

Solution

What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop?

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 `HashMap` instance then this is not an issue. 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.

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 the `HashMap` in a `synchronized {}` block, or making use of the `Collections.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 the `HashMap` in memory and there must be some sort of object reference loop. That's the peril of using an unsynchronized collection with multiple threads.

So in my understanding, it's not a problem as long as in the application we are just accessing the HashMap in a multi-threaded environment?

If by "accessing" you mean "reading", then this is true with qualifications. You must make sure:

- All of the updates to the `HashMap` are completed before the threads are instantiated and the thread that creates the map also forks the threads

- The threads are only using the `HashMap` in read-only mode – either `get()` or iteration without remove

- There are no threads updating the map

If any of these conditions are not true then you will need to use a synchronized map instead.

Problem

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.

Original source

Related problems