集合上的线程安全迭代 [英] Thread-safe iteration over a collection

查看:22
本文介绍了集合上的线程安全迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道当使用 Collections.synchronizedXXX(例如 synchronizedSet())时,我们会得到底层集合的同步视图".

We all know when using Collections.synchronizedXXX (e.g. synchronizedSet()) we get a synchronized "view" of the underlying collection.

然而,这些包装器生成方法的文档声明我们必须在使用迭代器迭代集合时显式同步集合.

However, the document of these wrapper generation methods states that we have to explicitly synchronize on the collection when iterating of the collections using an iterator.

您选择哪个选项来解决这个问题?

Which option do you choose to solve this problem?

我只能看到以下方法:

  1. 按照文档说明进行操作:在集合上同步
  2. 在调用 iterator()
  3. 之前克隆集合
  4. 使用迭代器线程安全的集合(我只知道CopyOnWriteArrayList/Set)

另外一个问题:使用同步视图时 - 使用 foreach/Iterable 线程安全吗?

And as a bonus question: when using a synchronized view - is the use of foreach/Iterable thread-safe?

推荐答案

你已经回答了你的奖金问题:不,使用增强的 for 循环安全 - 因为它使用迭代器.

You've already answered your bonus question really: no, using an enhanced for loop isn't safe - because it uses an iterator.

至于哪种方法最合适 - 这实际上取决于您的上下文:

As for which is the most appropriate approach - it really depends on how your context:

  • 写入非常少吗?如果是这样,CopyOnWriteArrayList 可能是最合适的.
  • 集合是否足够小,迭代速度是否很快?(即您在循环中没有做太多工作)如果是这样,同步可能很好 - 特别是如果这种情况发生的频率不高(即您不会对集合产生太多争用).
  • 如果您正在做大量工作并且不想阻止其他线程同时工作,那么克隆集合的效果可能是可以接受的.

这篇关于集合上的线程安全迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆