Open In App

Deadlock in Single Threaded Java Application

Deadlock describes a situation where two or more threads are blocked forever because they are waiting for each other. There are many causes of deadlocks. Two or more threads can deadlock when the following conditions hold:

The Java Thread Analyzer detects these deadlocks that are caused by the inappropriate use of mutual exclusion locks. This type of deadlock commonly happens in multi-threaded applications. By this above definition, to arise a deadlock situation, we need threads or processes, but can we produce a deadlock using a single thread? The answer is YES. In simple words, deadlock means some action waiting for other activities to complete. A single-threaded application can produce deadlock,



We will create a simple Java program on how to achieve this.

ThreadTest.java class:






public class ThreadTest {
  
    public static void main(String[] args)
        throws InterruptedException
    {
  
        System.out.println("Begin - Thread");
  
        Thread.currentThread().join();
  
        System.out.println("End - Thread");
    }
}

In ‘ThreadTest.java’ class, when the main method executes a thread will be created internally. Now, we are getting that ‘currentThread()’ that is created and we are calling the ‘join()’ method on it.

Thread join(): The ‘join()’ method is a synchronization method that blocks the calling thread i.e., the thread that calls this method until the thread whose join() method is called has completed. The caller thread will be block indefinitely if the thread does not terminate. If a thread wants to wait until another thread is completed its execution, this ‘join()’ method will be called. While working with ‘Thread.join()’ method, we need to handle the Interrupted exception either using try/catch block or throws declaration as it is a checked exception.

Execution:

The above program compiles without any error but arises into a Deadlock situation. When the above program runs, it prints “Begin – Thread” and in the next step, join() is called on the current thread only.  Here, ‘join()’ method is called on the current thread, so the current thread is waiting to complete its execution only. Hence, a Deadlock situation occurs.

Output:

We will get the below output when the program runs.

Output

Like this, it will only print the ‘Begin – Thread’ and enter into deadlock. This will never print the ‘End – Thread’ and the application will stop only when we terminate it. So, a deadlock situation can be produced with a single thread also.

Article Tags :