7

I don't understand the rationale of this code, taken from javax.swing.event.EventListenerList docs:

protected void fireFooXXX() {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
        if (listeners[i]==FooListener.class) {
            // Lazily create the event:
            if (fooEvent == null)
                fooEvent = new FooEvent(this);                 
            ((FooListener)listeners[i+1]).fooXXX(fooEvent);
        }
    }
}
  1. Why is the list traversed backwards?
  2. Why is only every second listener called?

The event firing is implemented exactly this way in javax.swing.tree.DefaultTreeModel among others, so it's obviously me who's just not getting something.

Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169

3 Answers3

6

1.

One possible problem when traversing listeners is described in Swing Hacks item #94, and happens if one of them removes itself as a listener in it's implementation of fooXXX().

Consider this listener, that might remove itself after receiving the event:

public class FooListener implements EventListener {
   private int i;

   public FooListener(int i) {
       this.i = i;
   }

   public fooXXX(FooEvent foo) {
       System.out.println(i);
       if (i == 1) {
           ((FooEventSource)foo.getSource()).removeListener(this);
       }
   }
} 

and this implementation of the listener traversal:

public void fireFooXXX() {
   for (int i=0; i<listeners.size(); i++) {
      // Lazily create the event:
      if (fooEvent == null)
         fooEvent = new FooEvent(this);
      listeners.get(i).fooXXX(fooEvent);
   }
}

Now suppose we create a number of these listeners:

fooEventSource.addListener(new FooListener(0));
fooEventSource.addListener(new FooListener(1));
fooEventSource.addListener(new FooListener(2));
fooEventSource.addListener(new FooListener(3));

Firing the event would give the following output:

0
1
3

We would be looping over the listeners by index, from 0 to 3. At index 1 the listener removes itself from the internal array of listeners, causing listeners 2 and 3 to be shifted down to index 1 and 2. The loop continues with index 2 which now contains listener 3. Listener 2 has been skipped.

By iterating backwards this problem is eliminated since removing a listener would only shift the index of listeners that have already been called.

But

EventListenerList does not have this problem, since the add() and remove() methods are copy-on-write and the listener traversal in the suggested usage operates on the listener list instance returned by getListenerList() before the loop.

Some more discussions about it can be found in this thread, where the reasons seems to boil down to one of:

  • performance

  • event ordering (the last added listener will be the first to be notified)


2.

akf and Michael Borgwardt has already answered that the EvenListenerList stores the listener types in addition to the listeners. I guess the reason for this is that it makes it possible for a single EventListenerList to handle listeners of different types.

Johan Kaving
  • 4,870
  • 1
  • 27
  • 21
  • 1
    you didn't try that, did you? It's wrong as long as you follow the example in the api doc and simply invert the loop direction, that is grab the array of listeners once before looping: the field listeners is re-assigned on add/removeListener, the local reference is uneffected – kleopatra Oct 23 '11 at 11:30
  • Embarrassingly enough, I didn't... I have updated the answer accordingly but I am leaving the description of the problem that might occur when iterating over a list of listeners. Thanks for correcting me. – Johan Kaving Nov 08 '11 at 13:15
  • cool - and you dug up that ol' thread, wouldn't have expected _anything_ on the java.net forum being findable :-) The important points to take away from that and other threads are a) notification ordering is _unspecified_, it doesn't matter because listeners _must not_ rely on any sequence b) all listeners are equal, that is they _must_ (and are) notified independent of whether the (awt) event is consumed or not – kleopatra Nov 08 '11 at 13:28
5
  1. Probably performance considerations: backwards iteration is faster because comparison with 0 is a single machine code instruction - lots of former C programmers have that ingrained even though it's rather irrelevant nowadays. Note that there is no guarantee about the order in which listeners will be notified anyway.
  2. Look at the rest of the class - it stores the listeners' types as well to provide type safety.
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • Ah, ok. I just wonder why it isn't written like `FooListener[] listener = listenerList.getListeners(FooListener.class)`. Would be quite a bit cleaner, IMHO. Perhaps it has to do with performance as well. – Joonas Pulakka Oct 13 '09 at 11:18
  • I think the code example in the comment is outdated - the getListeners() method was added in Java 1.3 – Michael Borgwardt Oct 13 '09 at 11:46
  • 2
    maybe they are doing it backwards because they want to notify the last listener first? – Suraj Chandran Feb 05 '10 at 03:50
  • @Suraj Chandran there is no reason for wanting such a thingy, notification sequence is unspecified – kleopatra Oct 23 '11 at 11:31
4

to answer #2: Every second listener is called because the array that EventListenerList uses is set populated as an array of Listener-Type, Listener-Instance pairs.

akf
  • 38,619
  • 8
  • 86
  • 96