Java Multithreading – How Nested Monitor can cause DeadLock
I tried to code many programs which can help me to understand race condition, starvation, and deadlock practically. But I failed. Unknowingly I made this program which creates deadlock due improper synchronization.
public synchronized void acquire() throws Exception{
Thread.sleep(5000);
synchronized(lock){
wait(1);
}
}
public synchronized void modify() throws Exception{
Thread.sleep(5000);
synchronized(lock){
wait(1);
}
}
I added a tracer who explained me why both threads were getting blocked. You can integrate separate java thread tracer with your other threading programs.
Refer the output below to understand how improper nested monitoring took lock.
Output:
A:8
B:9
2012-03-07 19:54:57.625 :: [A:RUNNABLE,B:RUNNABLE]
2012-03-07 19:54:57.788 :: [A:RUNNABLE,B:BLOCKED]
2012-03-07 19:54:57.804 :: [A:TIMED_WAITING,B:BLOCKED]
2012-03-07 20:54:59.888 :: [A:RUNNABLE,B:BLOCKED]
2012-03-07 19:55:02.787 :: [A:TIMED_WAITING,B:TIMED_WAITING]
2012-03-07 19:55:02.788 :: [A:BLOCKED,B:TIMED_WAITING]
2012-03-07 19:55:07.787 :: [A:BLOCKED,B:RUNNABLE]
2012-03-07 19:55:07.787 :: [A:BLOCKED,B:BLOCKED]
Both threads are blocked
Deadlock detected in
Thread id: 9
Thread id: 8
Proper synchronization:
public void acquire() throws Exception{
Thread.sleep(5000);
synchronized(lock){
lock.wait(1);
}
}
public void modify() throws Exception{
Thread.sleep(5000);
synchronized(lock){
lock.wait(1);
}
}
You can solve this deadlock in another way as well. Its up to your need.
views


No Comments