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.
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 oldglobalObjwhile 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
Objectfor this purpose:Since
lockObjnever changes, you’ll always use the same lock – no problems.