Fire Events and Stay Bug Free #94
Chapter 12, Miscellany
|
475
HACK
So, what happened? The problem is obviously with the C listener, the one
that removes itself after being called. In fact, this removal is what causes the
disaster—the
ConcurrentModificationException
indicates that you’re trying
to change the
Collection
that underlies the
Iterator
, while iterating over it.
And It Gets Worse
At least Java 1.2 has a fail-fast exception for this. Back in Java 1.1, without
Collections, you might have used a
for loop instead of an Iterator to count
over the listeners. Example 12-14 shows what that might look like.
Good news: this doesn’t throw an exception. Bad news: this doesn’t throw
an exception, as seen in the console output:
[tonberry] cadamson% java PathologicalForLoopEventSource
A called
B called
C called
E called
Example 12-14. Using a for-loop to fire events
import java.util.*;
public class PathologicalForLoopEventSource
extends TestEventSource {
ArrayList listeners = new ArrayList( );
public void addListener (TestEventListener l) {
listeners.add (l);
}
public void removeListener (TestEventListener l) {
listeners.remove (l);
}
public void fireEvent (EventObject o) {
for (int i=0; i<listeners.size( ); i++) {
TestEventListener l = (TestEventListener) listeners.get(i);
l.handleEvent (o);
}
}
public static void main (String[] args) {
PathologicalForLoopEventSource pfles =
new PathologicalForLoopEventSource( );
pfles.test( );
}
}

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.