对象存储在线程安全收集线程中是否安全?(Are objects stored in thread safe collection thread safe?)

编程入门 行业动态 更新时间:2024-10-23 04:54:28
对象存储在线程安全收集线程中是否安全?(Are objects stored in thread safe collection thread safe?)

存储在线程安全集合(如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.

更多推荐

本文发布于:2023-08-02 20:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1380671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在线   线程   对象   程安全   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!