wood burning stoves*
The moose likes Beginning Java and the fly likes Deadlock Example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Deadlock Example" Watch "Deadlock Example" New topic
Author

Deadlock Example

vivek dhiman
Ranch Hand

Joined: Aug 05, 2011
Posts: 111


From the above code Can we say that Deadlock occuring? If yes the why? Thankx
R. Jain
Ranch Hand

Joined: Aug 11, 2012
Posts: 370
    
    1

vivek dhiman wrote:
From the above code Can we say that Deadlock occuring? If yes the why? Thankx


The above code may reach a deadlock state..
You see the order of synchronized block in both the threads.

1). 1st thread gets lock on d, and when it calls Thread.sleep(50), the second thread may get the CPU and it gets the lock on d1.
Now, again 2nd thread calls Thread.sleep(50).

2). At this point, it may be possible that, 1st thread can get the CPU, in which case, it will try to get lock on d1, but can't get it... So, it goes into Waiting State.
Again, 2nd thread may get the CPU, and will try to get lock on d, which is still with 1st thread... So, it will also go to waiting state.

So, both the threads will continuously get CPU and go to waiting state, thus leading into a Deadlock.

3). Now, suppose in point (1), When thread 1 goes to sleep, CPU is not allotted to thread 2, rather to a different thread. So, there is an equal chance for both threads to get CPU later on when it is free..
So, if thread 1 again gets the CPU, then in this case deadlock will not occur, because, it will try to get lock on d1, which is free..
THAT's IT

 
jQuery in Action, 2nd edition
 
subject: Deadlock Example
 
Similar Threads
Why won't the following Deadlock? Exam 2 q.16
join() method in Thread doesn't work as expected
Thread synchronization problem
Thread.sleep() and lock
deadlock?