Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 368
Mike Q Avatar asked Dec 21 '10 10:12

Mike Q


1 Answers

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.

like image 145
Volker Stolz Avatar answered Oct 23 '22 06:10

Volker Stolz