Friday 25 October 2019

Deadlock | what is deadlock |deadlock in java - Online Help

Let's discuss the important topic of java multithreading is a deadlock

Now, what is deadlock?  A deadlock is a special type of error that you need to avoid( that relates specifically to multitasking), which occurs when two threads have a circular dependency on a pair of synchronized objects.

For Example,

suppose one thread enters object X  and another thread enters the object Y. If the thread in X tries to call any synchronized method on Y, It will be blocked. however, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X it would have to release its own lock on Y so that the first thread could complete.

Deadlock | what is deadlock |deadlock in java - Online Help
Read: What is thread and life cycle of a thread


It may involve more than two threads and two synchronized objects.

Deadlock situations can arise that involve more than two threads. Assume that thread1 wait for a lock held by thread2.Thread2 waits for a lock held by thread3. Thread3 waits for a lock held by thread1.

Sample program for deadLock is:

class x
{
y b;
synchronized void x1()
{
System.out.println("starting x1");
b.y2();
}
synchronized void x2()
{
System.out.println("starting x2");
}
}
class y
{
x a;
synchronized void y1()
{
system.out.println("starting y1");
a.x2();
}
synchronized void y2()
{
System.out.println("starting y2");
}
}
class threadX entends Thread
{
x a;
ThreadX(x a)
{
this.a=a;
}
public void run()
{
for(int i=0;i<100000;i++);
a.x1();
}
}
class threadY entends Thread
{
y b;
ThreadY(y b)
{
this.b=b;
}
public void run()
{
for(int i=0;i<10000;i++);
b.y1();
}
}
class deadlockdemo
{
public static void main(String args[])
{
x a=new x();
y b=new y();
a.b=b;
b.a=a;
ThreadX t1=new ThreadX(a);
ThreadY t2=new ThreadY(b);
t1.start();
t2.start();
try
{
t1.join();
t2.join();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("successfully");
}
}

Read: interthread communication in java

Explanation:

In the following program class x has two synchronized methods named x1() andx2(). The x1() method calls the y2() method of that object. similarly, class y has two synchronized methods named y1() and y2(). The y1() methods call the x2()method of that object.

Class ThreadX extends and executes a loop that invokes the x1() method of the x object class. Class ThreadY extends and executes a loop that invokes the y1() method of the y object class.

I hope you understand what is a deadlock? if you have any queries or you find something wrong or have more information then please do comment.

No comments:

Post a Comment