What happens if two threads perform a get of one hashmap at the same time?

Muruganantham Mani

[I know a HashMap object is not synchronized if not done explicitly, so in a case where you have to write and read data in a hashmap from different threads you need to synchronize it (or use another object).
However in my case I am writing to the HashMap (put) only once and it is done at the beginnig. Once the HashMap is filled I am going to read it from different threads at the same time. Do I need to synchronize these reads?]

Synchronization needs to be done only when there is a chance of changing the data from different threads simultaneously. In your case, it is simply going to be a read, the synchronization is not required. If you need to remove or modify the values in the hashmap, then you [may] need to synchronize that.

For synchronizing a HashMap, you can use Collections.synchronizedMap(<your hashmap reference>) which will return a synchronized map for you, which is thread-safe.

Remember, synchronization will cause a performance problem. So, it needs to be used carefully, when really required.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact