What is a deadlock in multithreading? How can you prevent it?

A deadlock occurs when two or more threads each hold a lock the other needs and neither can proceed, so all involved threads block forever. It typically arises from multiple threads acquiring the same set of locks in inconsistent order.

Key Points

Example

Thread A locks account1 then tries to lock account2 for a transfer, while Thread B simultaneously locks account2 then tries to lock account1 — each thread now waits forever for a lock the other holds, which is fixed by always acquiring locks in a consistent order, such as by account ID.

Lock first = accountId1 < accountId2 ? lock1 : lock2;
Lock second = accountId1 < accountId2 ? lock2 : lock1;

first.lock();
try {
    second.lock();
    try {
        // transfer funds
    } finally {
        second.unlock();
    }
} finally {
    first.unlock();
}

Interview Tip

A concise interview answer is

A deadlock happens when threads each hold a lock the other needs, so both wait forever — classically caused by acquiring locks in inconsistent order. I prevent it by always acquiring locks in a fixed global order, keeping locked sections small, and using tryLock with a timeout so a thread can back off instead of blocking indefinitely.

Last updated: 16 July 2026

Previous question: Can a finally block cause unexpected behaviour or side effects?

Next question: What issues might arise when both method overloading and overriding are used in the same class hierarchy?

More Exception Handling interview questions

All Exception Handling questions