O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( );
}
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required