notify listener inside or outside inner synchronization

Posted by Jary Zeels on Stack Overflow See other posts from Stack Overflow or by Jary Zeels
Published on 2010-06-17T13:12:31Z Indexed on 2010/06/17 13:23 UTC
Read the original article Hit count: 372

Hello all,

I am struggling with a decision. I am writing a thread-safe library/API. Listeners can be registered, so the client is notified when something interesting happens. Which of the two implementations is most common?

class MyModule {
   protected Listener listener; 

   protected void somethingHappens() {
        synchronized(this) {
             ... do useful stuff ...
             listener.notify();
        }
    }
}

or

class MyModule {
   protected Listener listener; 

   protected void somethingHappens() {
        Listener l = null;

        synchronized(this) {
             ... do useful stuff ...
             l = listener;
        }
        l.notify();
    }
}

In the first implementation, the listener is notified inside the synchronization. In the second implementation, this is done outside the synchronization.

I feel that the second one is advised, as it makes less room for potential deadlocks. But I am having trouble to convince myself.

A downside of the second imlementation is that the client might receive 'incorrect' notifications, which happens if it accessed the module prior to the l.notify() statement.

thanks a lot

© Stack Overflow or respective owner

Related posts about api

Related posts about library