no_clue_so
no_clue_so

Reputation: 71

Should I use ConcurrentHashMap or HashMap if I threads don't change structure of map?

Do I need a ConcurrentHashMap in Java for this case:

Before, passing the HashMap to a bunch of threads, I initiate the map with all the keys necessary:

Key = "thread1Key", Value = null
Key = "thread2Key", Value = null
Key = "thread3Key", Value = null
...

Each task is part of a Runnable (executed by a thread) and is assigned to alter the value of ONLY 1 of those keys. It's preassigned. In other words, I don't need to worry about the case where multiple Runnables may alter the same key in the hashmap.

In this case is ConcurrentHashMap required or a regular HashMap would do? And why?

Thanks!

Upvotes: 3

Views: 243

Answers (3)

fgb
fgb

Reputation: 18559

A HashMap may stay structurally consistent in such a scenario, but there's also the issue of the visibility of its values. If a value is changed in one thread, then it is not guaranteed to be seen by the other threads. Or if it is, then it could also be inconsistent as it's not safely published between the threads.

Upvotes: 3

Suman
Suman

Reputation: 868

A regular map is sufficient if there are no removal of entries in map.

Upvotes: 0

Thomas
Thomas

Reputation: 182000

This usage of HashMap is safe without additional synchronization. The docs describe exactly your use case:

If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

Upvotes: 4

Related Questions