The Brittle Session Pruner
A clean-up routing utility throws a raw ConcurrentModificationException when clearing disconnected terminal lines.
The setup
You are writing a routine cleanup function to scan your server's open connection lists and drop channels that have gone cold. The logic performs flawlessly with lone entries but throws a fatal exception as soon as multi-node cluster sweeps drop elements under load.
The broken code
import java.util.*;
public class ChannelPruner {
public void dropInactiveNodes(List<String> liveSockets) {
// TRAP: Modifying a collection wrapper directly while traversing it
// using a standard enhanced for-loop invalidates internal index counters!
for (String socketId : liveSockets) {
if (socketId.contains("OFFLINE")) {
liveSockets.remove(socketId);
}
}
}
}
Hints
- Java's enhanced for-loop translates to an implicit Iterator behind the scenes.
- If you modify a list while iterating over it via any method other than the iterator's own remove() function, it crashes.
- Use explicit iterator handlers, or rely on modern Java 8+ lambda utilities like .removeIf().
The fix
import java.util.*;
public class ChannelPruner {
public void dropInactiveNodes(List<String> liveSockets) {
// Clean Fix: Leverage lambda expression engines to handle structural mutation safely
liveSockets.removeIf(socketId -> socketId.contains("OFFLINE"));
}
}
Why it breaks
The Bug: Modifying structural dimensions while iterating via an standard enhanced loop desynchronizes internal modification counters (modCount). This triggers an immediate ConcurrentModificationException crash.