Java Reference
In-Depth Information
A synchronized method is created by preceding its declaration with
synchronized
.
For any given object, once a synchronized method has been called, the object is locked
and no synchronized methods on the same object can be used by another thread of exe-
cution.
Other threads trying to call an in-use synchronized object will enter a wait state until
the object is unlocked.
When a thread leaves the synchronized method, the object is unlocked.
The synchronized Statement
Although creating
synchronized
methods within classes that you create is an easy and ef-
fective means of achieving synchronization, it will not work in all cases. For example, you
might want to synchronize access to some method that is not modified by
synchronized
.
This can occur because you want to use a class that was not created by you but by a third
party, and you do not have access to the source code. Thus, it is not possible for you to
add
synchronized
to the appropriate methods within the class. How can access to an object
of this class be synchronized? Fortunately, the solution to this problem is quite easy: You
simply put calls to the methods defined by this class inside a
synchronized
block.
This is the general form of a
synchronized
block:
Here,
objref
is a reference to the object being synchronized. Once a synchronized block has
been entered, no other thread can call a synchronized method on the object referred to by
objref
until the block has been exited.
For example, another way to synchronize calls to
sumArray( )
is to call it from within a
synchronized block, as shown in this version of the program: