Using HashMap in multithreaded environment

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.


This is a classical question. ArrayList and HashMap are not synchronized, while Vector and HashTable are. You should therefore use HashTable unless you are very careful defining mutexes yourself.

In other words, the methods in e.g. HashTable will ensure that no other thread is working with the HashTable at any given time. If you use a HashMap, you'd have to do that manually by ensuring that you synchronize on HashMap before you call the method.

Update: checkout @Gray's comment. It looks like wrapping HashMap with Collections.synchronizedMap(new HashMap()) is the way to go now.

EDIT: other posters have answered way better than I did. My answer, however, generated an interesting discussion on the use of the soon to be deprecated Vector, Stack, Hashtable and Dictionary classes, so I'm leaving the question here, as a head to the comments below. Thanks guys!