Part 4 of 6 · 2 min read
Two classic bugs
Changing the list and alien calls.
The first bug is changing the list while it is being walked. An observer may want to unsubscribe itself when notified, for example a "once only" listener. With a plain ArrayList, removing an element inside the for loop can throw a ConcurrentModificationException. In a test with three listeners where the first removes itself, the plain list threw the exception. With CopyOnWriteArrayList, the same test passes and the listener runs exactly once.
RoomListener[] once = new RoomListener[1];
once[0] = e -> { log.add("once"); board.unsubscribe(once[0]); };
board.subscribe(once[0]);
board.set("B2", true);
board.set("B2", false);
After these two calls the log holds "once" one time, since the second change finds the listener gone. EJ Item 79 shows the same problem in an observable set, and recommends CopyOnWriteArrayList, built for this use. Its mutation methods copy the whole array, which makes it slow for lists that change often. For observer lists, which change rarely and are walked often, it fits well.
The second bug comes from threads. If the subject calls observers while holding a lock, an observer is an alien method: the subject cannot know what it does. EJ warns that running such code inside a synchronized block may lead to exceptions, deadlock or damaged data. An observer might try to take another lock, or call back into the subject while it is half-updated. The remedy is to make the call outside the lock. Update the state inside the lock, take a snapshot of the observer list, release the lock, then notify. The copy-on-write list gives that snapshot for free.
GoF adds further pitfalls. Observers are unaware of each other, so a harmless-looking change in the subject may set off a chain of updates through observers and whatever depends on them. Loosely defined dependencies also cause needless updates that are hard to trace. An observer that is never removed also stays alive in memory, since the subject refers to it. Always unsubscribe when an observer's life ends.
Common mistake
Letting observers change the subject from inside onChange. This can start a loop of notifications, or leave the subject half-updated for the next observer. Keep observers short and let them schedule heavy work.
Check yourself:
1. Why did the plain ArrayList version throw?
2. What does "alien method" mean?
3. How do you avoid calling observers under a lock?