0

Is it fine/safe if I have multiple threads running in parallel and each thread uses the same HashMap instance? The HashMap object will only be used to read data. There will be no writing data to the HashMap in any of the threads.

To be clear, the HashMap instance is a member of a base class and I will be calling the background threads in its subclasses. Those threads will then refer to the HashMap object.

David Velasquez
  • 2,346
  • 1
  • 26
  • 46

1 Answers1

2

If the threads are only reading from the HashMap, then it is no problem. You will get into trouble when at least one thread is modifying the HashMap while others might be reading from it concurrently.

Java does have other Map implementations that are safe for concurrent use, such as java.util.concurrent.ConcurrentHashMap.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • Perhaps add the "this implementation is not synchronized" quote from https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html? – Andy Turner Apr 29 '16 at 14:41
  • @AndyTurner that's not really relevant when threads are only reading and not writing to the `HashMap`. – Jesper Apr 30 '16 at 07:49
  • Well, it sort of is. It says that it is necessary to synchronize when structurally modifying the map and reading it from multiple threads. Whilst this doesn't explicitly state that synchronisation is not necessary when only reading, I think this is implied by the absence. – Andy Turner Apr 30 '16 at 07:52