In Java should I copy a volatile reference locally before I foreach it
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.
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.
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.
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.
精彩评论