Java Reference
In-Depth Information
executes
method_2()
from inside
method_1()
, it will have acquired the object's monitor lock twice. When it exits
method_2()
, it will release the lock once; when it exits
method_1()
, it will release the lock the second time; and then
the object's monitor lock will be available for other threads for acquisition. The same argument applies to the call to
method_4()
from inside
method_3()
except that, in this case, the
MultiLocks
class object's monitor lock is involved in
the synchronization. Consider calling
method_3()
from
method_1()
, like so:
public class MultiLocks {
public synchronized void method_1() {
// some statements go here
this.method_2();
MultiLocks.method_3();
// some statements go here
}
// rest of the code remains the same as shown before
}
Suppose you call
method_1()
, like so:
MultiLocks ml = new MultiLocks();
ml.method_1();
When
ml.method_1()
is executed, the executing thread must acquire the monitor lock of the object
ml
. However,
the executing thread must acquire the monitor lock of the
MultiLocks.class
object to execute the
MultiLocks.
method_3()
method. Note that
ml
and
MultiLocks.class
are two different objects. The thread that wants to execute
the
MultiLocks.method_3()
method from the
method_1()
method must possess both objects' monitor locks at the
same time.
You can apply the same arguments to work with synchronized blocks. For example, you can have a snippet of
code like
synchronized (objectReference) {
// trying to synchronize again on the same object is ok
synchronized(objectReference) {
// some statements go here
}
}
It is time to take a deeper look into the workings of threads synchronization using an object's monitor. Figure
6-6
depicts how multiple threads can use an object's monitor.