Find the bug · #33 · Loops and closures Medium Java
Removing blocked users crashes
A nightly job removes blocked users from groups, and it crashes on most groups.
On this page
The report
Admins can block users, and a nightly job removes blocked users from every group. It crashes with ConcurrentModificationException on most groups, though a test with three members worked.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Members {
// Removes every blocked user from the group.
static void removeBlocked(List<String> members, Set<String> blocked) {
for (String m : members) {
if (blocked.contains(m)) members.remove(m);
}
}
}Read it, then pick a line.
Can a list change size while a for-each loop is walking through it?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
List<String> group = new ArrayList<>(List.of("Asha", "Ravi", "Meera", "Kabir"));
try {
Members.removeBlocked(group, Set.of("Asha"));
System.out.println(group);
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}It prints
ConcurrentModificationException
It should print
[Ravi, Meera, Kabir]
Show the answer: the bug, the fix, and how you’d find it
The bug (lines 4, 5)
Lines 4 and 5 remove from members while a for-each loop is iterating over it. The loop’s hidden iterator notices the list changed under it and throws ConcurrentModificationException on its next step. (Remove the second-to-last item and the loop happens to end before it checks, which is why the small test passed.) Use removeIf, or an explicit iterator’s own remove().
The fix
1class Members {2 // Removes every blocked user from the group.3 static void removeBlocked(List<String> members, Set<String> blocked) {4 for (String m : members) {5 if (blocked.contains(m)) members.remove(m);6 }4 members.removeIf(blocked::contains);7 }8}How you’d find it
- Reproduce with the first member blocked: it throws straight away.
- The stack trace ends in
ArrayList$Itr.next, inside the for-each loop’s iterator, not in your own code. - That exception means the list was modified while being iterated. The
members.remove(m)inside the loop does exactly that.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
List<String> g = new ArrayList<>(List.of("a", "b", "c", "d"));
Members.removeBlocked(g, Set.of("a", "c"));
check(g.equals(List.of("b", "d")), "both removed");Where else this bites
- The same when removing keys from a
HashMapwhile looping overkeySet(). - Python skips items quietly instead of throwing (see “Some expired items are never removed”).