Reputation: 2251
I have a Map<Sting, List<Object>>
that can be accessed from multiple Java class instances. This Map
is sometimes updated by a separate thread once in a while. The instances never write to any of the objects. They simply get one of the List
s and read the objects in them.
Should I be concerned about thread-safety for this at all? Only one thread is ever writing.
Upvotes: 0
Views: 49
Reputation: 311528
In a word - yes.
Depending on the implementation, put
ing to a Map
can change its internal structure, which may cause a concurrent get
operation to have undefined behavior (e.g., with HashMap
s, I've seen cases where get
never returns if a put
"interrupted" it in the middle).
You should use a Map
implementation that's threadsafe, such as a ConcurrentHashMap
.
Upvotes: 5
Reputation: 25784
Yes. Note that Map is an interface, not an implementation. The documentation of several Map methods mentions:
The default implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.
Ensure to use a concurrent implementation like ConcurrentHashMap.
Upvotes: 1