• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Do I need to lock in this situation?

 
ciaran_cahill
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Any help with this would be much appreciated!!

In the B&S assignment I have an update() method in my database class (updating objects in the main ArrayList I use to hold Contractor details).

I use two ReentrantLocks - one for the main list of Contractor objects, and the other for the list of Contractor objects that are currently locked (to keep track of them). I am locking them both in the same order everywhere, and then unlocking them in the same order everywhere so as to avoid deadlock.

The thing is I don't need to actually modify the list of lockedContractors in this method. Just the main list of Contractor objects that the contractorLock is watching over.

Do I need to lock on the lockedContractors here anyway just to avoid deadlock??


contractorLock.lock();
lockedContractors.lock();

try {

... Do the work of modifying the Contractor here

}
catch (Exception e){
// nothing here yet - should be logged
}
finally {

lockedContractors.unlock();
contractorLock.unlock();
}


Thanks!
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you don't need to.
One of the Coffman conditions is:
Hold and wait condition, which in fact says, that your thread would need to have one resource and ask for another. Once you acquire lock on contractorLock, then you are pretty sure, that all body in update method will execute and then release lock on contractorLock.
This thread won't acquire resource and then become blocked.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic