dcsimg
doubt on deadlock
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   JavaPassion_Passion
Posted On:   Wednesday, August 1, 2007 08:31 AM

Hai Gurus ,

I know taht Deadlock is a condition under which the progress of a program is halted as each
thread in a set attempts to acquire a lock already held by another thread in the
set.

But my doubt is taht how can the JVM allow a particular thread to access the lock on a object which is already holded by some other thread?

( As i read that no other thread can access a synchronized method when a object is locked.)

Re: doubt on deadlock

Posted By:   Edward_Harned  
Posted On:   Wednesday, August 1, 2007 12:34 PM

It's the A/B problem. Where both A and B are lock objects.


If threads 1 and 2 need both locks and lock in reverse order(Thread 1 -- Lock A, Lock B and Thread 2 -- Lock B, Lock A) then this can happen:


Thread 2 gets and holds the Lock for B. At the same time, Thread 1 gets and holds the lock for A.
Thread 2 cannot continue until it gets the lock for A, but Thread 1 holds that lock and it cannot continue until it gets the lock for B.


See the problem?

Re: doubt on deadlock

Posted By:   Robert_Lybarger  
Posted On:   Wednesday, August 1, 2007 09:24 AM

The inability to access a 'synchronized' (locked) object is what tends to cause the deadlock. If you're just looking for a mental example, consider two objects objA and objB, and a common resource objC. Now, objC has a pair of methods that are synchronized on one variable while needing to refer to the other variable:

Object valA, valB;
...
public void methodA() {
synchronized(valA) {
//modify valA
//...time passes...
//modify valB
}
}
public void methodB() {
synchronized(valB) {
//modify valB
//...time passes...
//modify valA
}
}

This is rather highly contrived -- I'm making it up for sake of simple example. Now then, if objA runs in one thread and calls objC.methodA() while at nearly the same time objB runs in another thread and calls objC.methodB(), then both will be waiting for each other to exit the sync block so that they can complete and exit their own sync block. Neither will succeed... though it depends a bit on the timing of when the threads hit the methods, and how long it takes to complete said methods.
About | Sitemap | Contact