Is it a problem that my listener implementation is making a new array every time the listener is fired?
I have an object in my design that has listeners. These listeners get fired on a certain event that can occur as many as 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 here is that someone can implement an eventFired
method which then turns around and waits for a synchronize
to an object that's being held by a different thread which is trying to add or remove a listener and waiting on a synchronized(this.listeners)
line.
So, I modified the notifyListeners
method thusly:
private 开发者_StackOverflowObjectListener[] 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'm worried about the impact of creating this array every time the object is fired, and the impact this will have on the memory usage of the application.
So I'm here to ask if there's a better way. I may have just found it, though. It would be easy enough to create the ObjectListener[]
every time I add or remove a listener and then just iterate through that with no synchronization every time the event fires. I'm going to make that change now, and then see if there's a better idea offered up here.
Use CopyOnWriteArrayList instead. The observation is that listener lists are typically inspected a lot more often than they are modified.
精彩评论