DeadlocksDeadlock Conditions & PreventionMedium⏱️ ~2 min

Timeouts and tryLock

Practical Technique
Timeouts do not prevent deadlock but limit its damage. If you cannot acquire a lock within a time limit, give up, release held locks, and retry.

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.

Timeout-Based Recovery
lock(A)successtryLock(B, 100ms)wait up to 100mstimeout? → unlock(A)Backoffsleep(random)retry

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.

Best Practice: Use timeouts as a safety net, not as the primary strategy. Combine with lock ordering for prevention, and timeouts for recovery when something unexpected happens.
💡 Key Takeaways
tryLock(timeout) attempts to acquire lock, gives up after timeout. Returns success/failure.
On timeout: release held locks, log warning, random backoff, retry. Breaks potential deadlock.
Random backoff prevents synchronized retries that would deadlock again.
Timeouts are mitigation, not prevention. Deadlock can occur, but you recover from it.
Combine with lock ordering: ordering prevents, timeouts recover from edge cases.
📌 Examples
1Java: if (!lockB.tryLock(100, TimeUnit.MILLISECONDS)) { lockA.unlock(); Thread.sleep(random); retry; }
2Go: select with time.After for timeout. If lock channel does not respond, take alternate action.
3Database: innodb_lock_wait_timeout. Transaction aborts if lock wait exceeds limit. Application retries.
← Back to Deadlock Conditions & Prevention Overview
Timeouts and tryLock | Deadlock Conditions & Prevention - System Overflow