Design Pattern

Deadlock Prevention and Lock Ordering

Clean Java-only production-ready implementation.


What Problem It Solves

A deadlock is a state in which every thread in a group holds a lock and waits for a lock that another thread in the group holds, so none of them can ever continue. Nothing crashes and nothing is logged. The threads simply stop, the CPU goes quiet, and every request that needs those locks times out until someone restarts the process. The bug needs an unlucky interleaving, so it passes every single threaded test and shows up under production load.

A deadlock needs four conditions to hold at the same time, called the Coffman conditions. They are useful in an interview because they turn the question of how to prevent deadlock into a checklist. You pick a condition, break it by design, and then say which one you broke.

ConditionWhat it meansIn the transfer exampleA fix that breaks it
Mutual exclusionA lock has at most one holder at a timeOnly one thread can hold the lock on account AAvoid the lock: compare and swap on a version number, immutable snapshots, or one owner thread per account
Hold and waitA thread keeps what it holds while it waits for moreThread 1 holds A and waits for BAcquire all locks at once, or never hold one lock while asking for another
No preemptionA lock can only be released by the thread that holds itNothing can take A away from thread 1tryLock with a timeout, so a thread preempts itself and gives its lock back, or a database that aborts a victim transaction
Circular waitA cycle of threads exists in which each waits for the nextThread 1 waits for thread 2 and thread 2 waits for thread 1One global lock order, so every wait points from a lower key to a higher key and no cycle can close

Breaking any single condition is enough. Mutual exclusion is rarely removable for a money transfer that must change two balances together, so real systems usually break circular wait with an ordering rule or break no preemption with a timeout and a retry.

The Classic Transfer Deadlock

Take two accounts, A and B, each holding 100. Thread 1 runs transfer(A, B, 10) and thread 2 runs transfer(B, A, 20). Each transfer locks its source account first and its destination second, which is the natural way to write it and the way it reads in the argument list.

Loading...

At t2 each thread holds one lock and asks for the lock the other one holds. Thread 1 waits for thread 2 and thread 2 waits for thread 1, which is the cycle. The gap between the first and the second lock call is only a few microseconds in a bare transfer, but it grows as soon as real work sits between them, such as a log call, a database call or a callback. As an illustration, if the gap is 2 microseconds and each direction receives 10,000 transfers a second on the same pair, two opposite transfers overlap inside the gap roughly 400 times a second (10,000 times 10,000 times 4 microseconds). A single threaded test never sees it.

The fix that interviewers expect first is to make both transfers lock in the same order. If account A has the smaller id, both threads lock A first.

Loading...

Thread 2 still waits, but it waits for thread 1 and thread 1 never waits for thread 2. The rule guarantees this in general. A thread that holds a lock with key k only ever asks for locks with a larger key, so any chain of waits has strictly increasing keys. A chain like that cannot loop back to its start, and the thread at the end of it, which holds the largest key, can always run.

The Fixes and the Condition Each One Breaks

Five fixes cover almost every interview answer. The table names the Coffman condition each one removes, so you can justify the choice instead of just naming a technique.

FixCondition it breaksHow it worksCost or risk
Global lock orderingCircular waitSort every lock set by one unique key and always acquire in that order, for example the smaller account id firstEvery code path must follow the rule, and the whole lock set must be known before the first acquire
tryLock with timeout and backoffNo preemptionAsk for the second lock with a timeout. On failure release the first lock, wait a random time and retryCan livelock without jitter, needs a retry cap, and the work before the failure must be safe to redo
Acquire all locks at onceHold and waitTake every needed lock in one atomic step, either under a master lock that guards acquisition or with an all or nothing tryLock that releases partial gainsA master lock serializes all acquisitions, and an all or nothing attempt needs rollback of partial gains and a retry
Single coarse lockCircular wait, because only one lock existsOne lock guards the whole structure, so no thread ever waits for a second lockNo parallelism, and every operation queues behind the slowest one
Avoid nested locking by redesigning the data flowHold and waitNever hold one lock while taking another. Debit under lock A, release it, then credit under lock B with a ledger entry between the steps, or give each account one owner thread and send it commandsThe state between the two steps is visible, so a failure in the second step needs a compensating action

A sixth idea breaks mutual exclusion itself. Keep a version number on each account and commit with compare and swap, retrying on conflict. Digital Wallet (Advanced) uses version checks like this, although its Java swap methods are themselves synchronized, so there the versions add optimistic validation on top of short locks. A true atomic compare and swap removes lock waits for single object updates, but a transfer that must change two objects together still needs a lock or a transaction around the commit.

Lock Ordering With Equal Keys

Lock ordering needs a total order, which means any two distinct locks must compare as strictly smaller or larger. Three situations break that, and each has a standard answer.

SituationWhat goes wrongFix
The same object on both sides, such as a transfer from an account to itselfA reentrant lock tolerates being taken twice, but a plain Python Lock or a non reentrant async mutex blocks the thread on itself foreverCompare identity first, then reject the request or treat it as a no-op, or lock only once
Different objects with the same key, such as sorting by owner name, by balance or by hashCodeNeither object is first, so two threads can pick opposite orders and the cycle is backOrder by a unique and immutable key such as an id from an atomic counter or a database primary key
A key that can only tie, such as System.identityHashCode, which is not guaranteed uniqueCollisions are rare, so the bug appears once in millions of calls and is nearly impossible to reproduceOn a tie take a global tie-break lock first and then both locks in any order, so tied pairs queue behind one another

The tie-break lock works because every thread that meets a tie must hold the tie-break lock for the whole operation, so two tied transfers can never be in the middle of acquiring the same pair at once. Threads that do not tie keep using the key order. The cost is paid only on a collision. The cleaner answer is to make ties impossible by giving every lockable object a unique id when it is created, which is what the programs on this page do with an AtomicLong in Java, a module counter in TypeScript and itertools.count in Python.

Lock Ordering With Dynamic Lock Sets

A transfer locks exactly two objects, but many designs lock a set that is only known at runtime, such as every product in a cart, every seat in a booking or every account in a batch settlement. The same ordering rule applies if you follow four steps.

  1. Resolve the full set of objects to lock before taking any lock, using read only lookups.
  2. Remove duplicates, because the same lock taken twice hangs a non reentrant lock and a cart can easily contain one product on two lines.
  3. Sort the set by the global key.
  4. Acquire in that order, run the critical section, and release in reverse order inside a finally block or a with statement.

If the set can grow after you start, for example when you discover that you also need an account whose key is lower than one you already hold, you cannot simply acquire it. Release everything and restart with the larger set, or take the late lock with tryLock and a timeout. Layered code can also use a lock hierarchy, where each kind of lock gets a rank, such as wallet before ledger before metrics, and a thread may only acquire locks of a higher rank than the ones it holds. When the locks are striped, which means a fixed array of locks chosen by hashing the key, two different keys can land on the same stripe, so deduplicate and sort the stripe indexes and not the keys.

Livelock and Starvation: The Cousins

Deadlock is one of three ways a concurrent program fails to make progress. The other two look different from the outside, and interviewers like to ask which one a given fix can cause.

FailureWhat the threads are doingCPUTypical causeFix
DeadlockBlocked, each waiting for a lock another one holdsIdleA cycle of lock waitsLock ordering, timeouts, detection and a victim
LivelockRunning and reacting to each other, but never finishingBusyBoth threads back off and retry in step, such as tryLock with the same pause every timeRandom jitter, exponential backoff, a retry cap, or a tie rule such as lower id goes first
StarvationOne thread rarely or never gets the lock while the others make progressBusyAn unfair lock that lets running threads barge in, or readers that keep a writer waitingA fair lock such as new ReentrantLock(true), a first in first out queue, or bounded batch sizes

The tryLock fix trades one failure for the other. If both threads fail to get the second lock, release the first and retry after exactly the same pause, they collide again and again without ever finishing. A random pause that grows toward a ceiling breaks the symmetry, which is why the programs on this page use jitter, and the retry cap turns an endless loop into a clear failure that the caller can handle. Fair locks remove starvation by granting the lock in arrival order, at the price of lower throughput, because a running thread is not allowed to reacquire the lock ahead of a waiter.

Detecting a Deadlock

Prevention breaks a Coffman condition by design. Avoidance, such as the banker's algorithm, grants a request only if the system stays in a safe state, which needs every thread's maximum demand in advance and is rare in application code. Detection lets the deadlock happen, notices it and recovers. You need detection even with good prevention, because one code path that ignores the lock order is enough to bring the cycle back.

The cheapest tool is a thread dump. In Java, jstack <pid>, jcmd <pid> Thread.print or kill -3 <pid> prints every stack, and when a cycle exists the dump ends with a section headed Found one Java-level deadlock that names each thread, the lock it waits for and the thread that holds it. In Python, faulthandler.dump_traceback_later(timeout) dumps every stack after a delay and py-spy dump does it from outside the process. Node has no blocked threads to dump. An async deadlock is just promises that never settle, so you find it with timeouts and with a metric for how long each lock has been held.

Inside the process, ThreadMXBean.findDeadlockedThreads() returns the ids of the threads that sit on a cycle, including threads waiting on a ReentrantLock, while findMonitorDeadlockedThreads() only covers synchronized monitors. The Java program below uses the first method and then interrupts the two threads. That recovery works because they wait with lockInterruptibly(). A thread blocked in plain lock() or in synchronized ignores interrupts and stays stuck until the process ends, which is a good reason to prefer interruptible or timed acquisition in code that might deadlock.

The general technique is a wait for graph. Each thread or transaction is a node, and an edge from T to U means that T waits for a lock that U holds. A deadlock exists exactly when the graph has a cycle, and a depth first search finds one in time proportional to the nodes plus the edges. Distributed Lock Manager keeps such a graph in its DeadlockDetector and rejects the acquire that would close a cycle. Databases do the same after the fact. PostgreSQL starts looking for a cycle once a lock wait has lasted deadlock_timeout, which is 1 second by default, and InnoDB checks as transactions begin to wait unless detection is switched off. Either one picks a victim, aborts it with an error, and expects the application to retry the whole transaction. Transaction Isolation and MVCC covers the row locks that these deadlocks come from.

Choosing Between the Fixes

No fix wins everywhere, so name the situation first and pick the fix that fits it. The table lists the situations that come up most often in machine coding rounds.

SituationBest fitWhy
A pair or a set of objects that all have unique ids, such as transfers and seat holdsGlobal lock orderingIt costs one comparison or one sort, and it makes the cycle impossible by construction
The lock set is only discovered during the work, or callbacks you do not control run under the locktryLock with timeout and jittered backoffYou cannot sort locks you cannot see, but you can always give up and try again
Small in-memory structure, short critical sections, low contentionA single coarse lockIt is the simplest correct answer, and contention only matters once profiling shows it
The two steps may happen separately and money in flight is acceptableAvoid nested locking, with a ledger entry or a saga between the stepsNo thread ever holds one lock while waiting for another, at the cost of a compensating action on failure
The state lives in a databaseOne transaction with rows locked in key order, plus a retry on the deadlock errorThe database already detects cycles, and ordered updates keep the victims rare
The lock spans several processesA lease with a time to live and a fencing tokenLease expiry is the preemption, because a holder that stalls loses the lock and the token rejects its late writes

A good interview answer states the default and the escape hatch together. Say that you will order locks by account id because the set is known, that a self transfer is rejected before locking, and that you would switch to tryLock with jitter if the design later had to call out to code that takes other locks.

Where It Shows Up in LLD Problems

These problems take locks on more than one object, or deliberately avoid doing so. The first four rows are the places where an ordering rule decides whether the design is correct, and the remaining rows show the other fixes from this page.

ProblemLocks it takesFix it uses
Digital WalletIn the Java and Python blueprints, P2PTransferCommand.execute() and undo() lock the source and destination wallets, lower id first.Global lock ordering. The TypeScript blueprint takes no lock because its transfer is one synchronous step.
Digital Wallet (Advanced)The Java transfer() nests two synchronized wallet monitors, lower wallet id first.Global lock ordering wrapped around an optimistic version check.
E-commerce Cart & CheckoutIn the Java and Python blueprints, OrderService.placeOrder() sorts the cart's product ids, takes each product lock in that order and releases them in reverse.Global lock ordering over a dynamic lock set.
Restaurant Reservation SystemIn the Java and Python blueprints, Table.bookAll() and releaseAll() lock every table of a reservation in id order, check all of them, then insert into all or none. The TypeScript blueprint runs the same steps with no await between them.Global lock ordering over a dynamic lock set, because a large party may need several combined tables.
Movie Booking (BookMyShow)The Java and Python createBooking() sort the seat ids, but lock, reserve and unlock each seat in turn and roll back the seats already held if one fails.Ordering plus not nesting locks. No thread holds two seat locks at once, so the sort keeps the order predictable and becomes essential if a design ever holds several seat locks together.
SplitwiseOne lock for the whole service, taken in addExpense() and settleUp() in all three blueprints.A single coarse lock. With one lock there is nothing to order, at the price of no parallelism between independent expenses.
Inventory ManagementOne ReentrantLock per Product, and each service call takes one product lock at a time.Avoiding nested locking. Product.reserve() decides inside the product lock whether stock fell below the threshold and notifies the low stock observers only after it releases the lock, so an observer that locks a second product cannot create the nesting this page warns about.
Distributed Lock ManagerA wait for graph in DeadlockDetector and leases that expire.Detection of a cycle before the acquire is granted, and preemption through the lease.

Common Interview Traps

TrapWhyFix
Locking the source and then the destination in argument orderOpposite transfers between the same pair form a cycle, and the bug hides until real loadSort the two locks by a unique key before acquiring either one
Ordering by hashCode() or by a non unique fieldTwo different accounts can compare equal, so each thread may pick its own orderUse an id assigned once from an atomic counter or a primary key, or add a tie-break lock
Transfer from an account to itselfA non reentrant lock such as a Python Lock blocks the thread on its own lock foreverCheck from == to before locking and return or reject
Calling a callback, listener or overridable method while holding a lockThe foreign code may take other locks, which adds edges to the wait graph that nobody can seeCollect the event under the lock and fire it after releasing, or hand it to a queue
One code path that locks in the opposite orderA rule that is followed in nine places and broken in the tenth still deadlocksPut acquisition in one helper that takes the whole set and sorts it, and review any direct lock call
Using tryLock and retrying immediately with the same pauseBoth threads fail, release, retry together and fail again, which is a livelockAdd random jitter that grows with each attempt and cap the number of retries
Forgetting finally or with around the second lockAn exception after the first acquire leaves a lock held forever, and the next caller hangsPair every acquire with a try and finally that releases it, or use with in Python
Believing the GIL or a single threaded runtime rules out deadlockPython locks still deadlock across threads, and in Node a task that awaits while holding an async mutex deadlocks with another taskApply the same ordering rule to async mutexes and avoid awaiting I/O while holding a lock
Answering with a timeout alone and no retry policyA timeout detects the cycle but does not say what happens next, and the same request may cycle againState the policy: release, back off with jitter, retry a bounded number of times, then fail the request

How to Present in an Interview

"A transfer touches two accounts, so two opposite transfers could each hold one lock and wait for the other. That is a circular wait, so I will break it with a global order. Every account gets a unique id when it is created, and every transfer locks the smaller id first. A transfer from an account to itself is rejected before any lock is taken. If the lock set becomes dynamic I will deduplicate and sort it first, and if I ever have to call code I do not control while holding a lock, I will switch to tryLock with a timeout and jittered backoff."

Close by naming the proof. Start many threads that move money in both directions, give them a deadline of a few seconds, and assert that every worker finished and that the total money is unchanged. The drivers in the code tabs below do exactly that, and they also run the unordered version first so that the failure is visible and not just claimed.

When You Do Not Need Lock Ordering

Ordering only matters when a thread holds one lock and asks for another. If every operation takes a single lock at a time, as the inventory service does with its per product locks, there is no wait chain to order. If a design guards the whole structure with one lock, there is nothing to order either. And in a single threaded runtime such as Node, a critical section that never awaits cannot be interrupted, so it cannot deadlock. The risk returns the moment an await sits between two lock acquisitions, which is why the TypeScript program below deadlocks even though JavaScript has one thread.

Two related designs remove locks altogether. Giving each account a single owner thread and sending it commands, as in the Command Pattern, means no other thread touches the balance, though a transfer between two owners then needs a two step protocol with a compensating action. A pool is also a lock in disguise. In an Object Pool Pattern, a task that borrows one connection and then waits to borrow a second from the same pool can use up the whole pool across tasks and stall, which is hold and wait again. Borrow once per task, or size the pool so that nested borrows cannot exhaust it.

Implementation

One Program Per Language, Three Phases Each

Every tab is a complete program that ends on its own in a couple of seconds. Phase 1 runs the naive transfer, which locks the source and then the destination, with a small test hook that makes the unlucky interleaving certain, and then notices the deadlock without hanging. Phase 2 runs the ordered transfer from eight workers in both directions and checks that all of them finish and that the total money is unchanged. Phase 3 runs the tryLock variant with timeouts and jittered backoff, which also finishes and also conserves the money.

LanguageHow phase 1 notices the deadlockHow the stuck threads are cleaned up
JavaThreadMXBean.findDeadlockedThreads() returns the two thread ids on the cycle, and the driver prints who waits for whomBoth threads wait with lockInterruptibly(), so interrupt() makes them give up, and they are daemon threads in any case
TypeScriptA deadline race: the two transfers do not settle within 300 ms, and both async mutexes report that they are held with one waiter eachNothing to clean up, because pending promises hold no handle and the Node process exits when the event loop is empty
PythonThe second lock is taken with acquire(timeout=0.3), and both threads report that they gave upEach thread releases its first lock on the way out, and the threads are daemons so they never block exit

The programs use a unique id from a counter as the ordering key, skip a transfer from an account to itself before locking, release locks in reverse order inside finally or with, and widen the window between the two lock calls with a short pause in phases 2 and 3, so the ordered code is tested in the same window that deadlocks the naive code. The balances have no overdraft check, because the demo is about lock behaviour and the conserved total is the invariant under test.

// โ”€โ”€โ”€ DEADLOCK PREVENTION AND LOCK ORDERING (JAVA) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// WHAT WE ARE SHOWING:
// 1. naiveTransfer locks the source then the destination, so two opposite
//    transfers deadlock. ThreadMXBean.findDeadlockedThreads() finds the cycle,
//    and interrupting the two threads lets the program exit.
// 2. orderedTransfer always locks the account with the smaller id first, so no
//    cycle of waits can form (it breaks the circular wait condition).
// 3. tryTransfer gives back the first lock when the second stays busy, then
//    retries after a random pause (the thread preempts itself, so waits are bounded).
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

final class Account {
    private static final AtomicLong SEQ = new AtomicLong();

    final long id = SEQ.incrementAndGet();   // unique and never reused, so it never ties
    final ReentrantLock lock = new ReentrantLock();
    private long balance;

    Account(long balance) { this.balance = balance; }

    long balance() { return balance; }       // read after the workers are done
    void move(long delta) { balance += delta; }
}

final class Bank {
    // Stands for work done between the two lock calls (20 microseconds).
    static void pause() { LockSupport.parkNanos(20_000); }

    // BAD: lock order follows the argument order, so A->B and B->A can cycle.
    static void naiveTransfer(Account from, Account to, long amount, CountDownLatch bothHoldFirst)
            throws InterruptedException {
        from.lock.lockInterruptibly();
        try {
            bothHoldFirst.countDown();
            bothHoldFirst.await();           // test hook: makes the unlucky interleaving certain
            to.lock.lockInterruptibly();
            try {
                from.move(-amount);
                to.move(amount);
            } finally {
                to.lock.unlock();
            }
        } finally {
            from.lock.unlock();
        }
    }

    // FIX 1: one global order (smaller id first) for every caller.
    static void orderedTransfer(Account from, Account to, long amount) {
        if (from == to) return;              // equal keys: nothing to move, never lock one lock twice
        Account first = from.id < to.id ? from : to;
        Account second = first == from ? to : from;
        first.lock.lock();
        try {
            pause();
            second.lock.lock();
            try {
                from.move(-amount);
                to.move(amount);
            } finally {
                second.lock.unlock();
            }
        } finally {
            first.lock.unlock();
        }
    }

    // FIX 2: tryLock with a timeout, release everything on failure, back off with jitter.
    static boolean tryTransfer(Account from, Account to, long amount, AtomicInteger retries)
            throws InterruptedException {
        if (from == to) return true;
        for (int attempt = 0; attempt < 50; attempt++) {
            if (from.lock.tryLock(5, TimeUnit.MILLISECONDS)) {
                try {
                    pause();
                    if (to.lock.tryLock(5, TimeUnit.MILLISECONDS)) {
                        try {
                            from.move(-amount);
                            to.move(amount);
                            return true;
                        } finally {
                            to.lock.unlock();
                        }
                    }
                } finally {
                    from.lock.unlock();
                }
            }
            retries.incrementAndGet();
            int cap = 2 << Math.min(attempt, 4);   // 2, 4, 8, 16, 32 ms ceiling
            Thread.sleep(ThreadLocalRandom.current().nextInt(1, cap + 1));
        }
        return false;
    }
}

public class Main {
    interface Task { void run() throws Exception; }

    static Thread daemon(String name, Task task) {
        Thread t = new Thread(() -> {
            try {
                task.run();
            } catch (InterruptedException e) {
                System.out.println("  [" + Thread.currentThread().getName() + "] interrupted while waiting");
            } catch (Exception e) {
                System.out.println("  unexpected: " + e);
            }
        }, name);
        t.setDaemon(true);                   // a stuck thread must not keep the JVM alive
        return t;
    }

    static long total(List<Account> accounts) {
        long sum = 0;
        for (Account a : accounts) sum += a.balance();
        return sum;
    }

    static boolean runAll(List<Callable<Void>> jobs) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(jobs.size());
        try {
            List<Future<Void>> futures = pool.invokeAll(jobs, 5, TimeUnit.SECONDS);
            for (Future<Void> f : futures) if (!f.isDone() || f.isCancelled()) return false;
            return true;
        } finally {
            pool.shutdownNow();
        }
    }

    public static void main(String[] args) throws Exception {
        // ---- Part 1: the deadlock, found by the JVM and then broken ----
        Account a = new Account(100), b = new Account(100);
        CountDownLatch bothHoldFirst = new CountDownLatch(2);
        Thread t1 = daemon("T1 A->B", () -> Bank.naiveTransfer(a, b, 10, bothHoldFirst));
        Thread t2 = daemon("T2 B->A", () -> Bank.naiveTransfer(b, a, 20, bothHoldFirst));
        t1.start();
        t2.start();

        ThreadMXBean mx = ManagementFactory.getThreadMXBean();
        long[] stuck = null;
        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
        while (stuck == null && System.nanoTime() < deadline) {
            Thread.sleep(20);
            stuck = mx.findDeadlockedThreads();
        }
        System.out.println("naive transfer: deadlock detected = " + (stuck != null));
        if (stuck != null) {
            for (ThreadInfo info : mx.getThreadInfo(stuck)) {
                System.out.println("  " + info.getThreadName() + " waits for a lock held by " + info.getLockOwnerName());
            }
        }
        t1.interrupt();
        t2.interrupt();
        t1.join(1000);
        t2.join(1000);
        System.out.println("after interrupt: A=" + a.balance() + " B=" + b.balance() + " (no money moved)");

        // ---- Part 2: ordered locking, many threads and opposite directions ----
        List<Account> accounts = new ArrayList<>();
        for (int i = 0; i < 4; i++) accounts.add(new Account(1000));
        List<Callable<Void>> jobs = new ArrayList<>();
        for (int w = 0; w < 8; w++) {
            jobs.add(() -> {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                for (int i = 0; i < 2_000; i++) {
                    Account from = accounts.get(rnd.nextInt(4));
                    Account to = accounts.get(rnd.nextInt(4));
                    Bank.orderedTransfer(from, to, 1);
                }
                return null;
            });
        }
        boolean finished = runAll(jobs);
        System.out.println("ordered transfers: 8 workers finished = " + finished
            + ", total = " + total(accounts) + " (expected 4000)");

        // ---- Part 3: tryLock with timeout and jittered backoff ----
        Account x = new Account(500), y = new Account(500);
        AtomicInteger retries = new AtomicInteger();
        AtomicInteger gaveUp = new AtomicInteger();
        List<Callable<Void>> tryJobs = new ArrayList<>();
        for (int w = 0; w < 4; w++) {
            final boolean forward = w % 2 == 0;
            tryJobs.add(() -> {
                for (int i = 0; i < 300; i++) {
                    boolean ok = forward ? Bank.tryTransfer(x, y, 1, retries) : Bank.tryTransfer(y, x, 1, retries);
                    if (!ok) gaveUp.incrementAndGet();
                }
                return null;
            });
        }
        boolean tryFinished = runAll(tryJobs);
        System.out.println("tryLock transfers: workers finished = " + tryFinished + ", gave up = " + gaveUp.get()
            + ", total = " + (x.balance() + y.balance()) + " (expected 1000)");
        System.out.println("backoffs taken under contention: " + retries.get());
    }
}

๐Ÿ’ฌReview

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...