Java Reference
In-Depth Information
per.doSomething
would never be able to acquire the lock because it would be con-
sidered already held, and the thread would permanently stall waiting for a lock it can never
acquire. Reentrancy saves us from deadlock in situations like this.
Listing 2.7. Code that would Deadlock if Intrinsic Locks were Not Reentrant.
2.4. Guarding State with Locks
construct protocols for guaranteeing exclusive access to shared state. Following these proto-
cols consistently can ensure state consistency.
Compound actions on shared state, such as incrementing a hit counter (read-modify-write) or
lazy initialization (check-then-act), must be made atomic to avoid race conditions. Holding
a lock for the
entire duration
of a compound action can make that compound action atomic.
However, just wrapping the compound action with a
synchronized
block is not suffi-
cient; if synchronization is used to coordinate access to a variable, it is needed
everywhere
that variable is accessed
. Further, when using locks to coordinate access to a variable, the
same
lock must be used wherever that variable is accessed.
It is a common mistake to assume that synchronization needs to be used only when
writing
to
shared variables;
this is simply not true
. (The reasons for this will become clearer in
Section