O'Reilly logo

Developing Java Beans by Robert Englander

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

Serializing Event Listeners

Event-source objects keep references to their target event listeners, either directly or indirectly through a support object. It’s very important to recognize that these listeners may not be serializable. For instance, if you keep a Vector of event listeners, an attempt will be made to serialize the listeners when the Vector is serialized. One possible solution is to mark the collection of event listeners as transient. But we certainly don’t want to ignore the listeners, as some or all of them may very well be serializable. The best we can do is to serialize those listeners that can be serialized, and skip the others. Let’s look at a simple example class called SimpleTemperature that fires a TemperatureChangeEvent to its registered listeners. References to those listeners are kept in a Vector called listeners. Since we don’t know if the elements of listeners are serializable, we mark listeners as transient. We won’t actually be serializing listeners at all, only those elements of it that are serializable. We really don’t even need to construct the Vector until an event listener is added, so we won’t create it until it’s needed. The code illustrating this is next.

public class SimpleTemperature { // collection of temperature change listeners protected transient Vector listeners = null; public synchronized void addTemperatureChangeListener(TemperatureChangeListener l) { // if the vector doesn't exist yet, create it now if (listeners == null) { listeners ...

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