title: Is it a problem that my listener implementation is making a new array every time the listener is fired?
body: <p>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.</p>
  
  <p>I was doing something like this:</p>
  
  <pre><code>private void notifyListeners(ObjectEvent o) {
      synchronized (this.listeners) {
          for (ObjectListener l: this.listeners)
              l.eventFired(o);
      }
  }
  </code></pre>
  
  <p>The problem here is that someone can implement an <code>eventFired</code> method which then turns around and waits for a <code>synchronize</code>to an object that's being held by a different thread which is trying to add or remove a listener and waiting on a <code>synchronized(this.listeners)</code> line.</p>
  
  <p>So, I modified the <code>notifyListeners</code> method thusly:</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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 <code>ObjectListener[]</code> 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.</p>