I'm reading J. Bloch's "Effective Java" and now I'm at the section about for-each
vs for-loop
. He mentioned three cases where we couldn't use the for-each
loop and one of them is the following:L
Parallel iteration— If you need to traverse multiple collections in parallel, then you need explicit control over the iterator or index variable, so that all iterators or index variables can be advanced in lockstep (as demonstrated unintentionally in the buggy card and dice examples above).
The case is not quite clear to me, I can't imagine an example.
The first thought that popped into my head was that it was just about iterating the same collection in multiple threads but it's probably not what he meant. I don't see any restrictions preventing us from doing so (read-only). Actually:
public class MyRunnable implements Runnable{
private Collection<String> col;
//CTOR ommmited
public void run(){
for(String s : col){
//print o, not modify
}
}
Then we just start some threads with the same instance. So, we're not afraid of getting ConcurrentModificationException
(JavaDocs) because we perform read-only access, even by multiple threads simultaneously.
What's wrong?