I have a simple code as below to test the deadlock
public class ClassB {
public synchronized void fooB(Classs A) throws InterruptedException{
System.out.print("Thread : " + Thread.currentThread().getName()+ " entered to fooB \n");
Thread.sleep(1000);
System.out.print("ClassB locked the fooA \n");
A.lastA();
}
public synchronized void lastB(){
System.out.print("I am lastB \n");
}
}
And Also I have another class called ClassA:
public class ClassA {
public synchronized void fooA(ClassB B) throws InterruptedException{
System.out.print("Thread : " + Thread.currentThread().getName()+ " entered to fooA \n");
Thread.sleep(1000);
System.out.print("ClassA locked the fooB \n");
B.lastB();
}
public synchronized void lastA(){
System.out.print("I am lastA \n");
}
}
So, now I have another code that calls these classes and causes a deadlock as below :
public class DeadLockTest implements Runnable {
ClassA ca=new ClassA();
ClassB cb=new ClassB();
public DeadLockTest() throws InterruptedException{
new Thread(this).start();
ca.fooA(cb);
}
public void run() {
try {
cb.fooB(ca);
} catch (InterruptedException ex) { ....
}
}
}
As you can see the first thread locks fooB using ca.fooA(cb) and the second thread locks fooA using cb.fooB(ca) and Nobody has any lock over lastA and lastB methods. It means these methods are supposed to be available but they are not available. Why? The threads have just lock over fooA and fooB. So, why for example the first thread can't use lastB() and the second one has not access to lastA() while there is no lock on these two methods?
Deadlock in java is a programming situation where two or more threads are blocked forever.
Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other. This usually happens when multiple threads need the same locks but obtain them in different orders. Multithreaded Programming in Java suffers from the deadlock situation because of the synchronized keyword.
The process of creating a deadlock is simple. First execute the first update statement from the first transaction and then execute the first update statement from the second transaction. This will create locks on table1 and table2. Now execute the second update statement from transaction1.
When used on a method, the synchronized
keyword implicitly locks on this
-- well, on the monitor associated with this
. Objects have monitors; methods do not. So the monitor being used for fooA()
is the same monitor being used on lastA()
. That's why you have the deadlock.
Please read up on synchronized
before you go any further...
This looks fairly straight forward. It's a typical circular shared resource scenario. A needs B to continue and B needs A to continue.
Locks:
Thread 1 -> ClassB -> ClassA
Thread Main -> ClassA -> ClassB
Processing Order:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With