Java Reference
In-Depth Information
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 ob-
ject 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 does 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 has set the lock that
prevents any other synchronized method from starting.
NOTE
There is 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 con-
trolled by synchronization.
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 in some other
thread.
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
Figure