2

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?

4
  • Please provide specific code examples. Commented Jan 15, 2015 at 22:28
  • Should synchronize your getters and setters for the members in your complex object. Commented Jan 15, 2015 at 22:33
  • Make the attributes that can be changed and read by multiple threads volatile - that will ensure that values updated by one thread are seen by other threads. It does not help when threads change a value at the same time though (that would require synchronization or use of concurrent (Atomic) classes). Commented Jan 15, 2015 at 23:12
  • 1
    Folks, not every question has to have code. This question seems quite clear as it stands. Commented Jan 15, 2015 at 23:27

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.