zero said:
I don't think it's very common to remove a listener as a result of an
event - and notice I didn't even provide a removeMyEventListener method,
I think you'd be surprised. The other day I had a little demonstration
program that changed Look & Feel in response to a JList selection. The
NPE surprised me (not that I should be surprised by NPEs with my time
served). The change of L&F removed the PL&F's event listener, but it was
still present in the to be fired array. When it did get fired, the UI
delegate had be uninstalled. A quick EventQueue.invokeLater solved the
problem. Of course, when you install a new PL&F, it's listeners are now
later in the event list than the application's listeners.
Come to think of it, there is a technique (common within Swing itself)
where the listener maintains a weak reference to the object it mutates.
If the reference has been cleared, it removes itself in response to the
firing.
so in the code snippet it wouldn't even be possible ;-) But yeah you're
Even in the snippet you could have issues with listeners being added
during the firing, as you are using an Iterator.
right, it could happen. Making a copy of the list first seems like a
viable solution - though I wonder if there isn't a more elegant way.
Seems elegant to me. Perhaps I'm just used to that sort of thing. In 1.5
there's even java.util.concurrent.CopyOnWriteArrayList. Funny how things
become intuitive once learnt.
IMHO EventListenerList would be more useful if it implemented List or Map
(since it "maps" the listener type to the listener).
I don't see the use case for doing so. Also, it's a multimap rather than
a map, as it maps one type onto many listeners.
Any idea why listeners are usually fired in reverse order?
It's traditional? I think the original thinking was that even if a
listener removed itself, working backwards means that the unfired part
of the list is unaffected. Irrelevant with the current stronger
guarantees, but you don't want to go messing with behaviour unless you
have to.
Tom Hawtin