user384842
user384842

Reputation: 1975

What guarantees are provided if one thread mutates an object already in one of the concurrent collections?

If thread one puts a mutable object A into a concurrent collection, like a ConcurrentSkipListMap, I understand that this is thread-safe in the sense that if thread 2 'get's the object A from the collection, it is guaranteed to be fully visible.

However, if thread one has mutated object A while it is in the collection, does getting it by thread two still provide the same full visibility guarantee?

Upvotes: 0

Views: 52

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501586

However, if thread one has mutated object A while it is in the collection, does getting it by thread two still provide the same full visibility guarantee?

No, definitely not. The concurrency guarantees only apply to the collection itself. Once you've fetched the element from the collection, it's just a reference in a normal way - so even if there was a memory barrier at the end of the "get" operation, there'd still be the possibility of something like:

 Thread 1                   Thread 2

   get
                              get
                              mutate
   read

... and after both get operations had occurred, the collection is irrelevant.

Concurrent collections should be used for:

  • Immutable types which are naturally safe to use from multiple threads
  • Types which are mutable, but which you never mutate
  • Types where you apply explicit synchronization etc to ensure safety

Upvotes: 2

Related Questions