❮ Previous Next ❯

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.

❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved