cbender
cbender

Reputation: 2251

Is there a thread safety issue with multiple Java class instances reading the same Map simultaneously?

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 Lists 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

Answers (2)

Mureinik
Mureinik

Reputation: 311528

In a word - yes.

Depending on the implementation, puting to a Map can change its internal structure, which may cause a concurrent get operation to have undefined behavior (e.g., with HashMaps, 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

aled
aled

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

Related Questions