Skip to content

Instantly share code, notes, and snippets.

@parttimenerd
Last active December 30, 2025 09:29
Show Gist options
  • Select an option

  • Save parttimenerd/3db1c2e493e26f2c1990007e2d901310 to your computer and use it in GitHub Desktop.

Select an option

Save parttimenerd/3db1c2e493e26f2c1990007e2d901310 to your computer and use it in GitHub Desktop.
A simple deadlock demo application
class DeadlockDemo {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
private static final Object lock3 = new Object();
private static final Object lock4 = new Object();
public static void main(String[] args) throws InterruptedException {
// Create deadlock threads
Thread deadlock1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1: Holding lock1...");
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock2...");
synchronized (lock2) {
System.out.println("Thread 1: Acquired lock2");
}
}
}, "DeadlockThread-1");
Thread deadlock2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2: Holding lock2...");
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock1...");
synchronized (lock1) {
System.out.println("Thread 2: Acquired lock1");
}
}
}, "DeadlockThread-2");
// Create second deadlock with different locks
Thread deadlock3 = new Thread(() -> {
synchronized (lock3) {
System.out.println("Thread 3: Holding lock3...");
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Thread 3: Waiting for lock4...");
synchronized (lock4) {
System.out.println("Thread 3: Acquired lock4");
}
}
}, "DeadlockThread-3");
Thread deadlock4 = new Thread(() -> {
synchronized (lock4) {
System.out.println("Thread 4: Holding lock4...");
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Thread 4: Waiting for lock3...");
synchronized (lock3) {
System.out.println("Thread 4: Acquired lock3");
}
}
}, "DeadlockThread-4");
// Start all deadlock threads
deadlock1.start();
deadlock2.start();
deadlock3.start();
deadlock4.start();
deadlock1.join();
deadlock2.join();
deadlock3.join();
deadlock4.join();
System.out.println("All threads started. Deadlocks will occur shortly...");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment