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:
- Threads that are already holding locks request for new locks.
- The requests for new locks are made concurrently by the threads.
- Two or more threads form a circular chain in which each thread waits for a lock which is held by the next thread in the same chain.
- Two or more threads are waiting for each other to complete their respective execution.
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,
- If we have locks that are not re-entrant and a thread attempts to reacquire a lock that it owns already (or)
- If the same thread is waiting to complete the execution of itself like a recursive call.
We will create a simple Java program on how to achieve this.
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.
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.
We will get the below output when the program runs.
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.