Thanks for the interview question —
Q: Can you iterate over a LinkedList while another thread adds or removes elements? How might you make it thread safe?
If a long linked list is super busy with a lot of add/remove, then we may never finish iterating — we get ConcurrentModificationException every time.
I feel solution depends on length of the list, how critical is iteration vs add()/remove(), performance requirement etc.
I feel your initial idea is plausible — make a copy of the entire linked list before iterating. But when we make a copy, we need to iterate — chicken and egg problem.
How about iteration-free copying? Get a node, copy it, then read the “nextNode” pointer to reach the next node. This way I implement my own loop. Must handle concurrent modification. Not easy, but at least I don’t get exceptions. In contrast, Similar home-made solution is harder on vector/hashtable/deque as their reallocation is more complex.
I also like your 2nd idea of a custom linked list, where add() operations are customized. This is fine if iteration can finish quickly or add() is infrequent. However, If add()/remove() are time-critical, then we need other solutions.
If we need to iterate a long linked list that’s super busy, then the __design__ is probably wrong. Why not use a database?
Alternatively, split the long linked list into shorter lists. Easier to iterate.