存储在线程安全集合(如CopyOnWriteArrayList)中的对象是否安全? 让我们说存储的对象是可变的(不是线程安全的)然后集合(这里是CopyOnWriteArrayList)是线程安全的事实提供了对存储在其中的引用的线程安全性的任何保证吗?
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?
最满意答案
不,对象不是线程安全的; 如果两个线程更改了从CopyOnWriteArrayList检索到的可变对象,那么它们将导致数据争用。
如果集合是线程安全的,那么这意味着两个线程可以在不破坏集合的情况下添加/删除集合中的对象(例如,ArrayList不是线程安全的,因此如果两个线程都尝试将对象添加到集合中,那么一个或两个对象可能会丢失),但是仍然需要同步集合中的对象以使它们成为线程安全的。
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.
更多推荐
发布评论