Java Reference
In-Depth Information
Synchronized Methods
You can make a subset (or indeed all) of the methods for any class object mutually exclusive, so that
only one of the methods can execute at any given time. You make methods mutually exclusive by
declaring them in the class using the keyword synchronized . For example:
class MyClass {
synchronized public void method1() {
// Code for the method...
}
synchronized public void method2() {
// Code for the method...
}
public void method3() {
// Code for the method...
}
}
Now, only one of the synchronized methods in a class object can execute at any one time. Only when
the currently executing synchronized method for an object has ended can another synchronized method
start for the same object. The idea here is that each synchronized method has guaranteed exclusive
access to the object while it is executing, at least so far as the other synchronized methods for the class
object are concerned.
The synchronization process makes use of an internal lock that every object has associated with it. The
lock is a kind of flag that is set by a process, referred to as locking or a lock action , when a synchronized
method starts execution. Each synchronized method for an object checks to see whether the lock has
been set by another method. If it has, it will not start execution until the lock has been reset by an
unlock action . Thus, only one synchronized method can be executing at one time, because that method
will have set the lock that prevents any other synchronized method from starting.
Note that there's no constraint here on simultaneously executing synchronized
methods for two different objects of the same class. It's only concurrent access to any
one object that is controlled.
Of the three methods in myClass , two are declared as synchronized , so for any object of the class, only
one of these methods can execute at one time. The method that isn't declared as synchronized, method3() ,
can always be executed by a thread, regardless of whether a synchronized method is executing.
It's important to keep clear in your mind the distinction between an object that has instance methods
that you declared as synchronized in the class definition and the threads of execution that might use
them. A hypothetical relationship between three threads and two objects of the class myClass is
illustrated in the following diagram:
Search WWH ::




Custom Search