I have an object in my design that has listeners. These listeners receive dismissal from a specific event, which can occur up to a hundred times per second.
I was doing something like this:
private void notifyListeners(ObjectEvent o) {
synchronized (this.listeners) {
for (ObjectListener l: this.listeners)
l.eventFired(o);
}
}
The problem is that someone can implement a method eventFiredthat then rotates and waits for an synchronizeobject that is being held by another thread that is trying to add or remove a listener and wait on synchronized(this.listeners).
So, I modified the method notifyListenersas follows:
private ObjectListener[] getObjectListeners() {
synchronized (this.listeners) {
return this.listeners.toArray(new ObjectListener[this.listeners.size()]);
}
}
private void notifyListeners(ObjectEvent o) {
ObjectListener[] listeners = this.getObjectListeners();
for (ObjectListener l: listeners)
l.eventFired(o);
}
I worry about the effect of creating this array every time an object is started, and its effect on memory usage in the application.
, , , . , , . ObjectListener[] , , . , , .