synchronized object set to null synchronized object set to null multithreading multithreading

synchronized object set to null


This will almost certainly break the synchronization abstraction -- I wouldn't be confident that thread2 will see the change immediately. You should never change the reference of the object you're synchronizing on, much less set it to null, which will cause a NullPointerException on any further attempts to synchronize on it.


First let me emphasise that modifying a variable that is used for synchronization is a terribly bad thing. obj1 should be final and never be touched if it is used as a monitor.

That being said, back to your question:

If JVM first executes Thread1, it synchronizes on obj1, sets it to null and the thread exits. The second thread wants to synchronize on obj1, NullPointerException will be thrown. Because the modification of obj1 was made in synchronized block, it is guaranteed that Thread2 will see updated value (so: NullPointerException is guaranteed).

If Thread1 is interrupted after obtaining the lock on obj1 but before clearing the reference, Thread2 will lock on obj1 and wait until Thread1 finished. Then it will successfully enter the monitor because the object previously referenced by obj1 still exists.


synchronized synchronizes on the object, and not the reference. By setting obj1 (a reference) to null, thread2 can't synchronize on the object formerly pointed to by obj1, you'll get a NullPointerException instead.