Skip to main content

Java Interview Question: What is Deadlock and How to Create It in Java (With Example & Prevention)

 

🔹 Introduction

Deadlock is one of the most critical concepts in Java multithreading and is frequently asked in interviews.

👉 Interviewers often ask:
“What is deadlock? Can you create one in Java?”

In this article, we will:

  • Understand deadlock
  • Create a deadlock
  • Learn how to prevent it

🔹 What is Deadlock?

A deadlock occurs when two or more threads are waiting for each other indefinitely, and none of them can proceed.

👉 Simple idea:

  • Thread 1 holds Resource A and waits for B
  • Thread 2 holds Resource B and waits for A

💥 Both get stuck forever


🖼️ Visualization (Understand Easily)

Thread 1 → holds Lock A → waiting for Lock B
Thread 2 → holds Lock B → waiting for Lock A

Result: DEADLOCK

🔹 Java Code to Create Deadlock

public class DeadlockExample {

private static final Object lock1 = new Object();
private static final Object lock2 = new Object();

public static void main(String[] args) {

Thread t1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1 acquired lock1");

try { Thread.sleep(100); } catch (Exception e) {}

synchronized (lock2) {
System.out.println("Thread 1 acquired lock2");
}
}
});

Thread t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2 acquired lock2");

try { Thread.sleep(100); } catch (Exception e) {}

synchronized (lock1) {
System.out.println("Thread 2 acquired lock1");
}
}
});

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

🔍 Why Deadlock Happens

Deadlock occurs due to 4 conditions:

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

👉 All must be true


🔹 How to Prevent Deadlock

✅ 1. Lock Ordering

Always acquire locks in same order


✅ 2. Use Try Lock

Use timeout-based locking


✅ 3. Avoid Nested Locks

Reduce dependency between resources


✅ 4. Use Higher-Level APIs

Use:

  • ExecutorService
  • Concurrency utilities

🔹 Time Complexity

  • Not applicable (thread blocking issue)

🔹 Key Takeaways

✔ Deadlock = threads waiting forever
✔ Happens due to circular dependency
✔ Can be prevented using lock strategies
✔ Very important interview question


🔹 Conclusion

Deadlock is a critical concept in multithreading. Understanding how it occurs and how to prevent it is essential for backend developers.

🔗 Also Read

Comments

Popular posts from this blog

Top Java Interview Question: First Non-Repeating Character in a String

  🔹 Introduction Java interviews often include string-based questions. One of the most commonly asked questions is: 👉 Find the first non-repeating character in a string. In this article, we will solve it step by step in a simple and easy-to-understand way. 🔹 Problem Statement Given a string, find the first character that does not repeat. Example: Input: aabbcde Output: c 🔹 Approach To solve this problem efficiently: Count frequency of each character Maintain insertion order Traverse again to find the first character with frequency = 1 👉 We use LinkedHashMap because: It maintains insertion order Helps us find the first non-repeating character 🔹 Java Code import java . util . *; public class FirstNonRepeating { public static void main ( String [] args ) { String str = "aabbcde" ; Map < Character , Integer > map = new LinkedHashMap <>(); // Count frequency for ( char ch : str . to...

Java Interview Question: Separate Even and Odd Numbers Using Streams (With Examples)

  🔹 Introduction Separating even and odd numbers is a common Java interview question. It helps test your understanding of Java Streams, filtering, and partitioning . 👉 In this article, we will solve this using: Traditional approach Java Streams (modern approach) 🔹 Problem Statement Given a list of integers, separate even and odd numbers. Example: Input: [1, 2, 3, 4, 5, 6] Output: Even: [2, 4, 6], Odd: [1, 3, 5] 🔹 Approach 1: Using Loop (Basic) 💡 Explanation Traverse list Check number % 2 Store in separate lists 👨‍💻 Java Code import java . util . *; public class EvenOdd { public static void main ( String [] args ) { List < Integer > list = Arrays . asList ( 1 , 2 , 3 , 4 , 5 , 6 ); List < Integer > even = new ArrayList <>(); List < Integer > odd = new ArrayList <>(); for ( int num : list ) { if ( num % 2 == 0 ) { even . add ( num )...

Java Interview Question: Check if a String is a Palindrome

 🔹 Introduction String problems are very common in Java interviews. One of the easiest yet frequently asked questions is: 👉 Check whether a given string is a palindrome. Let’s understand how to solve it step by step. 🔹 Problem Statement A string is called a palindrome if it reads the same forward and backward. Example: Input: madam Output: Palindrome Input: hello Output: Not a Palindrome 🔹 Approach 1: Using Two Pointers (Best Method) Start one pointer from the beginning Start another pointer from the end Compare characters If all match → Palindrome 🔹 Java Code (Two Pointer Approach) public class PalindromeCheck { public static void main ( String [] args ) { String str = "madam" ; int left = 0 ; int right = str . length () - 1 ; boolean isPalindrome = true ; while ( left < right ) { if ( str . charAt ( left ) != str . charAt ( right )) { isPalindr...