Locks, conditions and AQS question 40 of 180 mid
How do you implement a timeout on acquiring a lock, and why would you?
synchronized (obj, timeout)- Correct:
lock.tryLock(500, MILLISECONDS), which returns false instead of waiting forever and gives you a way to back out of a deadlock Thread.sleepbefore entering the blockwait(timeout)on the lock object
synchronized has no timed acquisition at all: you wait forever or not at all. tryLock(time, unit)
returns a boolean, and that boolean is the whole point. It turns a potential deadlock into a failed
operation you can retry, log or fail fast on.
if (!lock.tryLock(500, MILLISECONDS)) {
throw new TimeoutException("could not acquire " + name);
}
try { ... } finally { lock.unlock(); }
The classic use is locking two accounts for a transfer: take the first, tryLock the second, and if
it fails release the first, back off a random amount and retry. That breaks the hold-and-wait
condition, so the deadlock cannot form. Note the bug people write here: calling unlock() in a
finally when tryLock returned false throws IllegalMonitorStateException.
Quiz yourself on Locks, conditions and AQS Suggest a correction