synchronized object set to null
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.
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.
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.
A quick fix is to make the object a simple array of 1 element and refer to the array for synchronization, e.g.,
Object[] obj1 = {null};
The element can be null without impacting the existence of the array. Granted, this still breaks the "rule" of not using the object itself in synchronization, but unless your code complicates matters elsewhere, this quick fix should work as expected.