• Post Reply Bookmark Topic Watch Topic
  • New Topic

thread-deadlock  RSS feed

 
sri jaisi
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class semaphore
{
Integer count1=null;
Integer count2=null;
semaphore()
{
i1=new Integer();
i2=new Integer();
}
public void up()
{
synchronized(count1)
{
count1=count1+1;
}
count2=count2+1;
}
synchronized public void down()
{
Synchronized(count1)
{
count1=count1-1;
}
count2=count2-1;
}
}
if two threads were started means will the above code results in a deadlock

thankz
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronization involves objects -- not references.



Here you are locking with the object referred to by the count1 variable. Then you are replacing the object with another object (done by autoboxing). If another thread execute this same code at this point, it will use a different synchronization lock.

But to answer your question (assuming you fix a couple of compile problems), I don't see how you can get a deadlock.

Henry
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Henry]: If another thread execute this same code at this point, it will use a different synchronization lock.

Not necessarily. Note that in order to synchronize, the thread must first access the count1 variable. Since this access must occur before the synchronization itself, that means the access itself is unsynchronized. So there's no guarantee that the thread will get an up-to-date view of what's in the count1 variable - it could be a slightly older copy. This in turn would mean that when two calls to up() occur near-sumultaneously from different threads, one of the calls has no effect.

I agree that there seems to be no chance of deadlock, from what we see here. But the synchronization shown here is highly unreliable, if the goal was to ensure the integrity of the data. Though I'm guessing maybe it's just a test of some kind, to compare the results of count1 and count2. Still, a simple way to get reliable results here would be to replace each "synchronized(count1)" with "synchronized (this)". That way threads would be reliably synchronizing on the same shared object. And with this change, there's also no need for Integer instances and autoboxing at all - simple int primitives can be used instead. Which will remove at least one of the compile errors in the current code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!