Java Reference
In-Depth Information
13.1.1. Polled and Timed Lock Acquisition
The timed and polled lock-acqusition modes provided by tryLock allow more sophist-
icated error recovery than unconditional acquisition. With intrinsic locks, a deadlock is
fatal—the only way to recover is to restart the application, and the only defense is to construct
your program so that inconsistent lock ordering is impossible. Timed and polled locking offer
another option: probabalistic deadlock avoidance.
Using timed or polled lock acquisition ( tryLock ) lets you regain control if you cannot ac-
quire all the required locks, release the ones you did acquire, and try again (or at least log the
failure and do something else). Listing 13.3 shows an alternate way of addressing the dynam-
ic ordering deadlock from Section 10.1.2 : use tryLock to attempt to acquire both locks,
but back off and retry if they cannot both be acquired. The sleep time has a fixed component
and a random component to reduce the likelihood of livelock. If the locks cannot be acquired
within the specified time, transferMoney returns a failure status so that the operation can
fail gracefully. (See [CPJ 2.5.1.2] and [CPJ 2.5.1.3] for more examples of using polled locks
for deadlock avoidance.)
Timed locks are also useful in implementing activities that manage a time budget (see Section
6.3.7 ) . When an activity with a time budget calls a blocking method, it can supply a timeout
corresponding to the remaining time in the budget. This lets activities terminate early if they
cannot deliver a result within the desired time. With intrinsic locks, there is no way to can-
cel a lock acquisition once it is started, so intrinsic locks put the ability to implement time-
budgeted activities at risk.
The travel portal example in Listing 6.17 on page 134 creates a separate task for each car-
rental company from which it was soliciting bids. Soliciting a bid probably involves some
sort of network-based request mechanism, such as a web service request. But soliciting a bid
might also require exclusive access to a scarce resource, such as a direct communications line
to the company.
We saw one way to ensure serialized access to a resource in Section 9.5 : a single-threaded
executor. Another approach is to use an exclusive lock to guard access to the resource. The
code in Listing 13.4 tries to send a message on a shared communications line guarded by
a Lock , but fails gracefully if it cannot do so within its time budget. The timed tryLock
makes it practical to incorporate exclusive locking into such a time-limited activity.
Search WWH ::




Custom Search