Search code examples
javajava.util.concurrentmemory-visibility

Java Concurrent Collections and visiblity


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?


Solution

  • 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.