在Java中,我应该在foreach之前在本地复制易失性引用吗
如果我有以下
private volatile Collection<Integer> ints;
private void myMethod()
{
for ( Integer i : ints )
{
...
}
}
ints 集合永远不会更改,但整个集合可能会被另一个线程替换(因此它是一个不可变集合)。
我应该在迭代之前在本地复制 ints 变量吗?我不确定它是否会被多次访问。即迭代集合,另一个线程替换集合,代码继续迭代,但使用新集合。
编辑:这个问题是有关 foreach 内部工作原理的其他信息相关。
If I have the following
private volatile Collection<Integer> ints;
private void myMethod()
{
for ( Integer i : ints )
{
...
}
}
The ints collection is never changed but the entire collection maybe replaced by another thread (so it's an immutable collection).
Should I be copying the ints variable locally before I iterate it? I'm not sure if it will be accessed multiple times. ie Iterating the collection, another thread replaces the collection, the code continues iterating but with the new collection.
EDIT : This question is relevant for additional info on how foreach works internally.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不必这样做。隐式地,代码无论如何都会执行
ints.iterator()
,并且从那时起仅在旧集合上使用该迭代器。You don't have to. Implicitly, the code will do an
ints.iterator()
anyway, and from that point on only use that iterator, on the old collection.应该不是必需的,因为 for 循环将获取一个 Iterator 一次并对其进行循环。
该迭代器与创建它的集合相关联。
所以它不会在循环中切换集合。
Should not be necessary, because the for loop will get an Iterator once and loop over that.
That Iterator is tied to the Collection that created it.
So it will not switch collections mid-loop.
我不认为这些人是对的。没错,您正在使用一次获得的迭代器进行迭代。但是,如果目标集合在迭代过程中发生更改,您将收到 ConcurrentModificationException。您可以轻松尝试。我相信,如果您的集合可以更改,您必须通过同步来跟踪它。
I do not think that the guys are right. That is right that you are iterating over using iterator obtained once. But if target collection is being changed during your iteration you get ConcurrentModificationException. You can easily try it. I believe that if you collection can be changed you have to track this by synchronization.