Java Reference
In-Depth Information
14.3. Synchronization
Recall the bank teller example from the beginning of this chapter. When
two tellers (threads) need to use the same file (object), there is a possib-
ility of interleaved operations that can corrupt the data. Such potentially
interfering actions are termed
critical sections
or
critical regions,
and you
prevent
interference
by
synchronizing
access to those critical regions. In
the bank, tellers synchronize their actions by putting notes in the files
and agreeing to the protocol that a note in the file means that the file
can't be used. The equivalent action in multithreading is to acquire a
lock
on an object. Threads cooperate by agreeing to the protocol that before
certain actions can occur on an object, the lock of the object must be ac-
quired. Acquiring the lock on an object prevents any other thread from
acquiring that lock until the holder of the lock releases it. If done cor-
rectly, multiple threads won't simultaneously perform actions that could
interfere with each other.
Every object has a lock associated with it, and that lock can be acquired
and released through the use of
synchronized
methods and statements.
The term
synchronized code
describes any code that is inside a
synchron-
ized
method or statement.
14.3.1.
synchronized
Methods
A class whose objects must be protected from interference in a multith-
readed environment usually has appropriate methods declared
synchron-
ized(
"appropriate" is defined later). If one thread invokes a
synchronized
method on an object, the lock of that object is first acquired, the meth-
od body executed, and then the lock released. Another thread invoking
a
synchronized
method on that same object will block until the lock is re-
leased: