Java Reference
In-Depth Information
One way to induce an ordering on objects is to use
System.identityHashCode
, which
sion of
transferMoney
that uses
System.identityHashCode
to induce a lock or-
dering. It involves a few extra lines of code, but eliminates the possibility of deadlock.
In the rare case that two objects have the same hash code, we must use an arbitrary means
of ordering the lock acquisitions, and this reintroduces the possibility of deadlock. To pre-
vent inconsistent lock ordering in this case, a third “tie breaking” lock is used. By ac-
quiring the tie-breaking lock before acquiring either
Account
lock, we ensure that only
one thread at a time performs the risky task of acquiring two locks in an arbitrary order,
eliminating the possibility of deadlock (so long as this mechanism is used consistently).
If hash collisions were common, this technique might become a concurrency bottleneck
(just as having a single, program-wide lock would), but because hash collisions with
Sys-
tem.identityHashCode
are vanishingly infrequent, this technique provides that last bit
of safety at little cost.