Hi @Shubham_Sharma,
Thank you so much for reaching out to us.
Below is the code of incrementCounter()
and decrementCounter()
as you can see that lock1
is first acquired by incrementCounter()
and required by decrementCounter()
later.
void incrementCounter() throws InterruptedException {
synchronized (lock1) {
System.out.println("Acquired lock1");
Thread.sleep(100);
synchronized (lock2) {
counter++;
}
}
}
void decrementCounter() throws InterruptedException {
synchronized (lock2) {
System.out.println("Acquired lock2");
Thread.sleep(100);
synchronized (lock1) {
counter--;
}
}
}
Since the lock1
is not released by incrementCounter()
so it can not be acquired by decrementCounter()
. The same goes for lock2
but opposite functions. Both of them cause deadlock.
I hope I have answered your question, but please feel free to ask if there is any confusion. Thank you so much.