Java Reference
In-Depth Information
The
CriticalSection2
class has six methods: three instance methods and three class methods. The
someMethod_1()
method is synchronized as the
synchronized
keyword is used in the method declaration. The
someMethod_11()
method
differs from the
someMethod_1()
method only in the way it uses the
synchronized
keyword. It puts the entire method
body inside the
synchronized
keyword as a block, which has the same effect as declaring the method
synchronized
.
The method
someMethod_12()
is different. It declares only part of the method's body as a
synchronized
block. There can
be more than one thread that can execute
someMethod_12()
concurrently. However, only one of them can be executing
inside the
synchronized
block at one point in time. Other sets of methods,
someMethod_2()
,
someMethod_21()
and
someMethod_22()
, are class methods, and they will behave the same way, except that class's object monitor will be used to
achieve the synchronization.
The process of acquiring and releasing an object's monitor lock is handled by the JVM. The only thing you need
to do is to declare a method (or a block)
synchronized
. Before entering a
synchronized
method or block, the thread
acquires the monitor lock of the object. On exiting the
synchronized
method or block, it releases the object's monitor
lock. A thread that has acquired an object's monitor lock can acquire it again as many times as it wants. However, it
must release the object's monitor lock as many times as it had acquired it in order for another thread to acquire the
same object's monitor lock. Let's consider the following code for a
MultiLocks
class:
public class MultiLocks {
public synchronized void method_1() {
// some statements go here
this.method_2();
// some statements go here
}
public synchronized void method_2() {
// some statements go here
}
public static synchronized void method_3() {
// some statements go here
MultiLocks.method_4();
// some statements go here
}
public static synchronized void method_4() {
// some statements go here
}
}
The
MultiLocks
class has four methods and all of them are
synchronized
. Two of them are instance methods,
which are
synchronized
using the reference of the object on which the method call will be made. Two of them are
class methods, which are
synchronized
using the reference of the class object of the
MultiLocks
class. If a thread
wants to execute
method_1()
or
method_2()
, it must first acquire the monitor lock of the object on which the method
is called. You are calling
method_2()
from inside the method
method_1()
. Since a thread that is executing
method_1()
must already have acquired the object's monitor lock and a call to
method_2()
requires the acquisition of the same
lock, that thread will reacquire the same object's monitor lock automatically when it executes
method_2()
from inside
method_1()
without competing with other threads to acquire the object's monitor lock. Therefore, when a thread