• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does this code has possible deadlock situation?

 
Woo Hwang
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at this code:
public class test extends Thread{
public static void main(String args[]){
final StringBuffer s1=new StringBuffer();
final StringBuffer s2=new StringBuffer();
new Thread(){
public void run(){
synchronized(s1){
s1.append("a");
synchronized(s2){
s2.append("b");
System.out.println(s1);
System.out.println(s2);
}
}
}
}.start();
new Thread(){
public void run(){
synchronized(s2){
s2.append("c");
synchronized(s1){
s1.append("d");
System.out.println(s1);
System.out.println(s2);
}
}
}
}.start();
}}
Regarding that these two thread run concurrently, what could be happened if the1st thread holds a lock on s1 and the 2nd thread holds on s2, then 1st one attemps to hold a lock on s2 and the 2nd one to hold on s1? Is it possible that this code is stuck in deadlock condition? So far I run this code, it doesn't cause any deadlock yet. But I think it has possibility. What do you think of this ?

[This message has been edited by Woo Hwang (edited August 09, 2001).]
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes this code has a race condition. Even if you run something a thousand times and there is no problem, that doesn't mean it will work the thousand and oneth. One of the fundemental rules of locking is that threads should always get locks in the same order. This code gets them in diffrent orders.
 
Ganesh Ram
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please come up with a scenario where deadlock would occur.
I cannot see any possibility as each operation is atomic.
No dependancy. I am referring to this particular piece of code.
 
Ganesh Ram
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sorry. I guess I am wrong. I could see the parenthesis clearly as they were formatted to the left.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code has indeed a pretty obvious race condition, as the two threads acquire their locks in a different order. Woo Hwang, please use [ CODE ] tags next time; your code is very hard to read without them. Thanks,
- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!