Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException on synchronized statement

Tags:

java

I tried to synchronize on an object in my code below:

public void myMethod() {
    synchronized (globalObj) {
        //Do something here
    }
}

The code is executed in one thread. The issue is that, another thread may set 'globalObj' to null. Then, 'synchronized (globalObj)' will throw NullPointerxception when 'globalObj' has been set to null by other threads.

What's the best practice to synchronize on an object so NullPointerException will not be thrown?

Thanks.

like image 606
Kai Avatar asked Jun 22 '11 00:06

Kai


1 Answers

You should not be synchronizing on a reference that itself may be changed. If another thread is allowed to replace globalObj, that means you might hold a lock to the old globalObj while another thread works on an entirely different one - the lock doesn't help you at all.

What you should do instead is have a separate Object for this purpose:

static final Object lockObj = new Object();

public void myMethod() {
  synchronized (lockObj) {
    // do something with globalObj here
  }
}

Since lockObj never changes, you'll always use the same lock - no problems.

like image 64
bdonlan Avatar answered Oct 25 '22 08:10

bdonlan