Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use HashMap<T> in a multi-threaded app? [duplicate]

Suppose we have multiple threads and we're dividing the possible keySet between the threads (i.e. key % thread_i) so there's no key collision.

Can we safely use HashMap<T> instead of ConcurrentHashMap<T>?

like image 991
yaseco Avatar asked Nov 22 '18 12:11

yaseco


People also ask

What will happen if you use HashMap in a multithreaded Java application?

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.

What is wrong with HashMap in multithreaded environment?

The HashMap is non-thread-safe and can not be used in a Concurrent multi-threaded environment. Comparatively, ConcurrentHashMap is a thread-safe and specially designed for use in multi-threaded and Concurrent environment.

Why HashMap should not be used in multithreaded environment can it cause an infinite loop as well?

The default capacity of HashMap is 16 and Load factor is 0.75, which means HashMap will double its capacity when 12th Key-Value pair enters in the map (16 * 0.75 = 12). When 2 thread tries to access HashMap simultaneously, then you may encounter infinite loop. Thread 1 and Thread 2 tries to put 12th key-value pair.

Can I use HashMap where multiple threads are accessing updating it explain further?

— Hashmap can solve performance issue by giving parallel access to multiple threads reading hashmap simultaneously. But Hashmap is not thread safe, so what will happen if one thread tries to put data and requires Rehashing and at same time other thread tries to read data from Hashmap, It will go in infinite loop.


1 Answers

No, for several reasons. Some (but not all) would be:

  1. HashMap rehashes your hash, so you won't even know what the actual key hash is.
  2. You'd have to look in HashMap's implementation to even know how many buckets there are.
  3. Resizing would have to copy state from the old array, and that wouldn't be safely published across threads.
  4. Other state, like the map's current size, wouldn't be safely updated.

If you constructed your map with a particular jvm implementation in mind, and made sure that your map never resized, and knew you'd never care about that extra state, it's maybe possible, in the strictest of senses. But for any practical purposes, no.

like image 110
yshavit Avatar answered Sep 20 '22 17:09

yshavit