Is it safe to add items to a LinkedList
while iterating?
class Worker {
final LinkedList<Foo> worklist = new LinkedList<>();
public void work() {
Iterator<Foo> iterator = worklist.iterator();
while (iterator.hasNext()) {
Foo foo = iterator.next();
doSomethingWith(foo);
}
}
public void doSomethingWith(Foo foo) {
// do something with foo
// and possibly add one (or more) foo's to the worklist
if (expression) {
worklist.add(new Foo());
}
}
}
If not, how can this behaviour be implemented in a safe and efficient way?
Note that this is not about a List
, but specifically about a LinkedList
. If it isn't safe, I'm asking about alternatives.