Saturday, May 10, 2014

Biggest Disadvantage of Lock over normal synchronized blocks

I mentioned in my other blog that I liked the lock mechanism introduced in Java 5. That holds true many of the API.  But, I have realized that there is a big flip side of the Lock mechanism over normal synchronized blocks.

If a thread acquires lock by calling lock() method of Lock and if that never releases the lock (which was supposed to be done by calling unlock() method) will make all others threads waiting for that lock starving. In fact, I am not sure if I can just call it as starving as the other threads can never acquire the lock.

I understand that, the documentation of Lock class clearly mentions this point,  not to fail calling unlock() as given below:

  Lock l = ...; 
     l.lock();
     try {
         // access the resource protected by this lock
     } finally {
         l.unlock();
     }
 
When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary.

How ever, how can we ensure that the developer does not miss this point. 

The good thing about normal synchronized blocks is that, once the execution of the synchronized block is completed that lock will automatically be released. One might counter argue that, what if the code inside synchronized block it self has some long running infinite loop kind of thing. But that kind of mistake is entirely different from the of mistake of missing releasing the lock specifically by the code. Calling unlock() is an additional responsibility, which is outside the business logic. 

Let me please know if you do not agree on this point. 

No comments:

Post a Comment