ReentrantLock - tryLock & Interruptibility
1. The “Why” ReentrantLock is a manual alternative to synchronized. We use it when we need to break Coffman’s Conditions for deadlocks. Specifically: Breaking “No Preemption”: With tryLock(), if a thread can’t get the lock, it can walk away instead of hanging. Breaking “Uninterruptible Wait”: With lockInterruptibly(), we can stop a waiting thread externally using thread.interrupt(). 2. Comparison: synchronized vs. ReentrantLock Feature synchronized ReentrantLock Flexibility Low (Block-scoped only). High (Can start lock in one method, end in another). Fairness No (Random thread gets the lock). Optional (Can grant lock to the longest-waiting thread). Timeout Support No (Waits forever). Yes (tryLock). Interruptibility No (Cannot be interrupted while waiting). Yes (lockInterruptibly). Syntax Simple (Automatic cleanup). Complex (Requires manual unlock() in a finally block). 3. The “Golden” Snippet: The Safe Transfer (No Deadlock) This snippet uses tryLock() to attempt to acquire two locks. If it fails to get the second one, it “preempts” itself by releasing the first one and trying again later. ...