aspose file tools*
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 Spring in Action this week in the Spring 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: 123


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

Joined: Aug 11, 2012
Posts: 375
    
    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

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Deadlock Example