简体   繁体   中英

Null check and listeners in java

Very often I see code like this:

Listener mListener;

public void setListener(Listener listener){
   mListener=listener;
}

public void fooFunction(){
   ...
   ...
   if (mListener!=null){
      mListener.notifyFoo();
   }
}

My question is: what if between the null check and the notifyFoo() another thread calls setListener(null)? Is that possible? or does the compiler make it atomical

You can synchronize methods

public synchronized void setListener(Listener listener){
   mListener=listener;
}

public synchronized void fooFunction(){
   ...
   ...
   if (mListener!=null){
       mListener.notifyFoo();
   }
}

Or if you want better granularity of locks

private Object monitor = new Object();

public void setListener(Listener listener){
   synchronized (monitor) {
       mListener=listener;
   }
}

public void fooFunction(){
   ...
   ...
   synchronized (monitor) {
        if (mListener!=null){
           mListener.notifyFoo();
       }
   }
}

You can avoid that by making your block Synchronized

public synchronized void setListener(Listener listener) {
    ....
}

public synchronized void fooFunction() {
    ....
}

The compiler doesn't make anything atomic by default. True, there is a chance of the listener being set to null between the two lines. You may use synchronized to avoid this.

Synchronisation is overkill here. Just take a copy of the member variable before checking it for null :

Listener mListener;

public void setListener(Listener listener){
   mListener=listener;
}

public void fooFunction(){
   ...
   ...
   Listener listener = mListener;
   if (listener!=null){
      listener.notifyFoo();
   }
}

Yes, it possible. Mark your fooFunction and setListener as synchronized and it should make this code multithread-safe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM