简体   繁体   中英

Are objects stored in thread safe collection thread safe?

Are the objects stored in a thread safe collection (like CopyOnWriteArrayList) thread safe? Let us say that the objects stored are mutable (not thread safe) then the fact that the collection (here CopyOnWriteArrayList) is thread safe provide any guarantee towards the thread safety of the reference stored in it?

No, the objects are not thread-safe; if two threads change a mutable object that they retrieved from a CopyOnWriteArrayList then they'll cause a data race.

If a collection is thread-safe then this means that two threads can add/remove objects from the collection without corrupting it (for example, an ArrayList is not thread-safe, so if two threads each try to add an object to the collection then one or both objects may be lost), however the objects in the collection will still need to be synchronized to make them thread-safe.

There are some guarantees, usually a thread safe storage is analogous to volatile variables in terms of memory effect.

volatile Foo var;              final Vector<Foo> vars = new Vector<>()

// thread 1                    // thread 1
foo.bar = bar;  [1]            foo.bar = bar;         [1]
var = foo;                     vars.set(0, foo);

// thread 2                    // thread 2
bar = foo.bar;  [2]            bar = vars.get(0).bar; [2]

//read[2] sees write[1]        // read[2] sees write[1]

Basically, writes before insertion should be visible to reads after retrieval.

The only thread-safe guarantee provided is that the objects will be “safely published”. That is, they will become visible at once for all threads (this includes the reference to the object and its internal state).

Example: if thread A writes X, and thread B reads, B is guarantee to see X as A left it. In other words, the read and write operations are consistent with the order in which they happen.

There are other ways to accomplish the same thing like using final , or volatile , or AtomicReference , or a lock (this is what the thread-safe collections are doing), or a static initializer. See the book “Java Concurrency in Practice” for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM