Practice ยท 1 of 3
Deadlock-free transfers with tryLock
Implement static boolean transfer(Account from, Account to, int amount) that can NEVER deadlock, using the tryLock-backoff pattern:
1. Acquire both account locks with tryLock() (use a small retry loop with backoff or a ordered attempt).
2. On success: check from.balance() >= amount, then move funds, release both locks, return true.
3. If either lock cannot be acquired: release whatever you hold and return false.
4. record Account(int id, int balance) won't do โ accounts must expose ReentrantLock lock() and be mutable; build a small static Account class inside Solution (id, balance, lock).
5. static boolean unsafeTransfer(...) doing the same with plain synchronized(from) nested synchronized(to) โ intentionally deadlock-prone in *structure* (tests only call it with distinct orderings to keep the suite deterministic; the lesson explains the hazard).
Difficulty: advanced
Back to lesson: Practice: Lock & CAS drills