Java DeadLock:

Deadlock is one of the very important point in multithreading. Deadlock is a situation where a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, as a result no thread can execute. This is known as deadlock. Lte's see a demo program on deadlock for better understanding:

DeadlockDemo.java
public class DeadlockDemo
{
public static void main(String[] args)
{
final String str1 = "Tapuuuuu";
final String str2 = "Silan"; // t1 tries to lock str1 then str2
Thread t1 = new Thread()
{
public void run()
{
synchronized (str1)
{
System.out.println("Thread 1: locked str1");
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
}
synchronized (str2)
{
System.out.println("Thread 1: locked str2");
}
}
}
};
Thread t2 = new Thread() // t2 tries to lock str2 then str1
{
public void run()
{
synchronized (str2)
{
System.out.println("Thread 2: locked str2");
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
}
synchronized (str1)
{
System.out.println("Thread 2: locked str1");
}
}
}
};
t1.start();
t2.start();
}

Output

Thread 1: locked str1
Thread 2: locked str2

If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thread 1 acquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.

 

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment