Only 49 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



  • Post Reply Bookmark Topic Watch Topic
  • New Topic

deadlock  RSS feed

 
nitin kumar
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MainStone
{
public static void main(String[] args)
{
System.out.println("Hello World!");
Flintstone fs=new Flintstone();
fs.fred(1);

}
}
class Flintstone
{
int field_1; private Object lock_1 = new int[1];
int field_2; private Object lock_2 = new int[1];

public void fred( int value )
{
synchronized( lock_1 )
{
synchronized( lock_2 )
{
this.barney(1);
try
{
Thread.sleep(5000);
}
catch(Exception e){e.printStackTrace();}
System.out.println("fred");
field_1 = 0;
field_2 = 0;
}
}
}

public void barney( int value )
{
synchronized( lock_2 )
{
synchronized( lock_1 )
{
System.out.println("barney");
field_1 = 0;
field_2 = 0;
}
}
}

}


Hi guys,

Here when I execute this the program prints barney but it should happen as I guess bcoz the lock_2 is still not released.Please clear me If Im wrong

bye
nitin
 
nitin kumar
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

Here when I execute this the program prints barney but it should not happen as I guess bcoz the lock_2 is still not released.Please clear me If Im wrong

bye
nitin
 
vinay prasad
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nitin,

When i ran this program, i am getting following o/p.


Hello World!
barney
fred
Press any key to continue . . .

Vinay
 
vinay prasad
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nitin,

I think the Flintstone Object "fs" has got the lock on both the objects lock_1 and lock_2. This should not cause deadlock problem in executing the whole program.

The Deadlock problem could have occured if there were two threads each having one lock and trying to waiting for another to release the lock.

< Guys Correct if i am not right >

Bye
Vinay
 
Yaroslav Chinskiy
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reazon you dont get a deadlock is because u only run one thread, 'main'. The same thread does not have to get a lock that it already holds.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!