This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Hi, I'm currently trying to find a practical solution to broadcast events. How do you do this? You don't just store all listeners in an array and iterate over this array do you? If you do so, how do you deal with listeners being removed while an event is broadcasted? Do you broadcast your events synchronously or with an additional thread?
I'd love to hear your reply on this, because I neither want to use arrays nor reflection.
There are a number of variations, but at the root of it, they all look pretty much like what you're describing with an array. Most of the time people will use a Collection of some kind rather than an array, so the Collection can manage growing and shrinking storage when listeners are added or removed.
The common solution to the "event handlers adding/removing listeners" problem is to clone the Collection of listeners before iterating over it.
Finally, whether or not to use a Thread to deliver events depends entirely on the application. Note that AWT and Swing use a thread whose sole purpose is to deliver events.
Originally posted by Ernest Friedman-Hill: ...The common solution to the "event handlers adding/removing listeners" problem is to clone the Collection of listeners before iterating over it...
Doesn't that kill performance?
"Finally, whether or not to use a Thread to deliver events depends entirely on the application. Note that AWT and Swing use a thread whose sole purpose is to deliver events." What advantages does using an additional Thread have? What do you think of AWTEventMulticaster's way of storing listeners (I personally think the idea behind it, namely using a chain of listeners, is quite elegant).
Or lock the collection for mutation in some way while notifications are being sent. This could be as simple as setting a boolean flag and having the addListener and removeListener methods wait (or fail) if that flag is set.
Enterprise Integration Patterns is mostly about messaging (JMS, MQ-Series) but the pub-sub patterns have some interesting variations. I listed a couple that I've used HERE before I found the EAI site. I made a little intermediary that manages subscriptions and is subclassed to forward events to subscribers. This is handy when there might be multiple publishers for the same message, or publisher instances might come and go over time.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi