CopyOnWriteArrayList 或向量
总之,
Vector类比ArrayList的优势在于它是同步的,因此保证了线程安全。然而,在 CopyOnWriteArrayList 和 Vector 之间,考虑到线程安全和性能,应该优先选择哪个。
All,
The edge Vector class has over ArrayList is that it is synchronized and hence ensures thread-safety. However, between CopyOnWriteArrayList and Vector, what should be the preferred considering thread safety and performance in consideration.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于使用模式 - 如果读取次数多于写入次数,请使用 CopyOnWriteArrayList,否则使用 Vector。
当 CopyOnWriteArrayList 的写入延迟较长(由于复制)但读取没有延迟时,Vector 会为每个操作引入较小的同步延迟。
另一个考虑因素是迭代器的行为 -
Vector
在迭代时需要显式同步(因此写入操作不能同时执行),而CopyOnWriteArrayList
则不需要。It depends on the usage pattern - if you have much more reads than writes, use
CopyOnWriteArrayList
, otherwise useVector
.Vector
introduces a small synchronization delay for each operation, whenCopyOnWriteArrayList
has a longer delay for write (due to copying) but no delay for reads.Another consideration is a behaviour of iterators -
Vector
requires explicit synchronization when you are iterating it (so write operations can't be executed at the same time),CopyOnWriteArrayList
doesn't.总的来说,这取决于读写操作的频率和性质,以及数组的大小。
您需要在您的环境中进行基准测试才能确定,但这里有一些一般原则:
array,那么即使 ArrayList 也是
线程安全(因为唯一的
非线程安全的修改是
那些修改列表的人)。因此
你会想使用
非同步数据结构,
ArrayList 或
CopyOnWriteArrayList 可能会
工作同样出色。
与写入相比,那么你会
倾向于更喜欢 CopyOnWriteArrayList,
因为数组复制开销是
仅在写入时发生。
小,那么制作成本
数组副本也会很小,
因此这将有利于
通过 Vector 进行 CopyOnWriteArrayList。
您可能还需要考虑其他两个选项:
Overall, it depends on the frequency and nature of read and write operations, and the size of the array.
You'll need to benchmark in your context to be sure, but here are some general principles:
array, then even ArrayList is
thread safe (since the only
non-thread-safe modifications are
those that modify the list). Hence
you would want to use a
non-synchronised data structure,
either ArrayList or
CopyOnWriteArrayList would probably
work equally well.
compared to writes then you would
tend to prefer CopyOnWriteArrayList,
since the array copying overhead is
only incurred on writes.
small, then the cost of making
array copies will also be small,
hence this will favour
CopyOnWriteArrayList over Vector.
You may also want to consider two other options: