Java Concurrent Collections and visiblity

231 Views Asked by At

I'm getting a little unsure about what to expect from Concurrent Collections (e.g. ConcurrentMap) regarding visibility of the data in the collection.

A: Thread1 puts a complex object and Thread2 gets it. Will all attributes be visible in Thread2?

B: Thread1 puts a complex object and later changes some attributes. Then Thread2 gets it, will all changes be visible in Thread2?

I guess B is false, and if so I should synchronize every access on the complex object?

2

There are 2 best solutions below

0
On BEST ANSWER

A: If the object is immutable or if the object is mutable but all the properties are set before the object is added to the collection then yes, they will be all visible. B: If no synchronisation mechanisms are in place then it is not guaranteed, it depends when the thread 2 accesses the object.

If you need this sort of behaviour guaranteed (i.e. the reading thread to be guaranteed to see all the modifications made by the mutator thread in a transactional-like manner) I suggest you set up a semaphoring mechanism. Even better, it would be simpler if you use immutable objects.

0
On

Pushing to a concurrent collection is defined as publishing it. See "Memory Consistency Properties" in the Package description.

This means if you just change a stored object, you do not get automatically a happens before relationship. You would need to make those changes synchronied/volatile or using a concurrent primitive itself.