← Back to Chapters

Deadlock in Advance Java

? Deadlock in Advance Java

? Quick Overview

A deadlock in Java occurs when two or more threads are blocked forever, each waiting for a resource held by another thread. Deadlocks are common in multithreaded and concurrent Java applications.

? Key Concepts

  • Occurs in multithreading environment
  • Threads wait indefinitely
  • No thread can proceed
  • System appears frozen

? Syntax / Theory

Deadlock happens due to four necessary conditions:

  1. Mutual Exclusion
  2. Hold and Wait
  3. No Preemption
  4. Circular Wait

? Code Example

? View Code Example
// Demonstration of deadlock using two threads and two resources
class DeadlockExample {

    static final Object resource1 = new Object();
    static final Object resource2 = new Object();

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            synchronized (resource1) {
                // Thread 1 locks resource1
                try { Thread.sleep(100); } catch (Exception e) {}
                synchronized (resource2) {
                    // Thread 1 tries to lock resource2
                }
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (resource2) {
                // Thread 2 locks resource2
                try { Thread.sleep(100); } catch (Exception e) {}
                synchronized (resource1) {
                    // Thread 2 tries to lock resource1
                }
            }
        });

        t1.start();
        t2.start();
    }
}

? Interactive Simulation

Thread 1
⬇ Locks
Resource 1
Thread 2
⬇ Locks
Resource 2
Status: Ready to Start

? Live Output / Explanation

What Happens?

Thread T1 holds resource1 and waits for resource2, while Thread T2 holds resource2 and waits for resource1. Both threads wait forever — causing a deadlock.

✅ Tips & Best Practices

  • Always acquire locks in a fixed order
  • Avoid nested synchronized blocks
  • Use timeout-based locks
  • Prefer higher-level concurrency APIs

? Try It Yourself

  • Modify code to avoid circular wait
  • Use ReentrantLock with timeout
  • Detect deadlock using Java VisualVM