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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With