Java Reference
In-Depth Information
You can declare both an instance method and a static method as synchronized . a constructor cannot be
declared as synchronized .
Tip
In the case of a synchronized instance method, the entire method is a critical section and it is associated with
the monitor of the object for which this method is executed. That is, a thread must acquire the object's monitor lock
before executing the code inside a synchronized instance method of that object. For example,
// Create an object called cs_1
CriticalSection cs_1 = new CriticalSection();
// Execute the synchronized instance method. Before this method execution
// starts, the thread that is executing this statement must acquire the
// monitor lock of the cs_1 object
cs_1.someMethod_1();
In case of a synchronized static method, the entire method is a critical section and it is associated with the
class object that represents that class in memory. That is, a thread must acquire the class object's monitor lock before
executing the code inside a synchronized static method of that class. For example,
// Execute the synchronized static method. Before this method execution starts,
// the thread that is executing this statement must acquire the monitor lock of
// the CriticalSection.class object
CriticalSection.someMethod_2();
The syntax for declaring a block of code as critical section is
synchronized(<objectReference>) {
// one or more statements of the critical section
}
The <objectReference> is the reference of the object whose monitor lock will be used to synchronize the access
to the critical section. The above syntax is used to define part of a method body as a critical section. This way, a thread
needs to acquire the object's monitor lock only, while executing a smaller part of the method code, which is declared
as a critical section. Other threads can still execute other parts of the body of the method concurrently. Additionally,
this method of declaring a critical section lets you declare a part or whole of a constructor as a critical section. Recall
that you cannot use the keyword synchronized in the declaration part of a constructor. However, you can use it inside
a constructor's body to declare a block of code synchronized . The following snippet of code illustrates the use of the
keyword synchronized :
public class CriticalSection2 {
public synchronized void someMethod_1() {
// method code goes here
// only one thread can execute here at a time
}
 
 
Search WWH ::




Custom Search