Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java DeadLock

Deadlock is a situation where no thread execute completely.

java-deadlock

Consider the above scenario. Let T1, T2 be two threads and R1, R2 be two resources respectively.

Here T1 is synchronizing(acquiring) R1 and trying to synchronize R2 for completing its execution.

Similarly T2 is synchronizing(acquiring) R2 and trying to synchronize R1 for completing its execution.

Here T1 is not able to synchronize R2 and T2 is not able to synchronize R1, hence T1 and T2 is not executing completely.

This is known as deadlock.

So deadlock is a situation where no thread execute completely.

Let’s see the program to represent deadlock.

DeadlockExample.java

public class DeadlockExample
{
	public static void main(String[] args)
	{
		String r1="Java";
		String r2="Express";

		//t1 trying to synchronize r1 and after 1000ms trying to synchronize r2
		Thread t1=new Thread()
		{
			public void run()
			{
				synchronized(r1)
				{
					System.out.println("in t1:r1 locked");
					try
					{
						Thread.sleep(1000);
					}
					catch(Exception e)
					{

					}
					synchronized(r2)
					{
						System.out.println("in t1:r2 locked");
					}
				}
			}
		};

		//t2 trying to synchronize r2 and after 1000ms trying to synchronize r1
		Thread t2=new Thread()
		{
			public void run()
			{
				synchronized(r2)
				{
					System.out.println("in t2:r2 locked");
					try
					{
						Thread.sleep(1000);
					}
					catch(Exception e)
					{

					}
					synchronized(r1)
					{
						System.out.println("in t2:r1 locked");
					}
				}
			}
		};

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

Output

in t1:r1 locked
in t2:r2 locked
from the above output we got clarity t1 is not accessing r2 and t2 is not accessing r1,
so t1 and t2 not executing completely.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext 

`