Timeouts and tryLock
How tryLock Works
Unlike regular lock() which blocks forever, tryLock() returns immediately with success/failure. tryLock(timeout) waits up to the timeout. If it fails, you can take corrective action.
The Timeout Pattern
Acquire first lock normally. Try to acquire second lock with timeout. If timeout expires, release first lock, log a warning, back off, retry. This breaks the deadlock by releasing held resources.
Why Random Backoff?
If two threads timeout and retry immediately at the same time, they might deadlock again. Random backoff desynchronizes them, making it likely one succeeds before the other retries.
Not Prevention, But Mitigation
Timeouts do not prevent deadlock - they let you recover from it. Deadlock can still occur; you just escape it. This is practical for production systems where perfect prevention is hard.