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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With