0

I find out one more benefit of using ReentrantLock over synchronized

Below code shows even if exception occurs in critical section lock is released(Using ReentrantLock )

void someMethod() {
     //get the lock before processing critical section.
   lock.lock();
   try 
   {
   // critical section 
   //if exception occurs
   }
   finally
   {
   //releasing the lock so that other threads can get notifies
   lock.unlock();
   }
}//end of method

Now by using synchronized

void someMethod() {
     //get the lock before processing critical section.
  synchronized(this) 
  {
    try 
    {
    // critical section 
    //if exception occurs
    }
    finally
    {
    //I don't know how to release lock

    }
  }

}//end of method

by comparing both the code I see that there is one more disadvantage in using synchronized block i.e If exception occurs in critical section than it is not possible to release the lock.

Am I right ?

Correct me if I am wrong please.

Is there anyway to release lock if exception occurrs in synchronized block ?

Javed Solkar
  • 162
  • 11
  • Ok so if exception occurs in middle of synchronized block than lock is released . right?(as per the link you gave me) @s.bandara – Javed Solkar May 14 '15 at 06:31
  • Intrinsic lock will be released after closing bracket of `synchronized` block is executed, you need not do that explicitly – Nitin Dandriyal May 14 '15 at 06:31
  • @JavedSolkar, correct! – s.bandara May 14 '15 at 06:33
  • Voting to re-open because the other question says nothing about the _Benefits of ReentrantLock_. `ReentrantLock` is more powerful than `synchronized`. That makes it "beneficial" in some situations, but it also makes it a dangerous tool. It's powers are; (a) you can decouple locking the lock from unlocking it (i.e., those things could happen in completely different methods); and (b) you can associate two or more separate condition variables with the same lock. Point (b) is especially relevant in a multi-producer, multi-consumer application. – Solomon Slow May 14 '15 at 13:47

1 Answers1

0

If an exception occurs in synchronized block the lock will still be released. So lock will be released in all circumstances.

The advantage with ReentrantLock is they use compare and sweep which performs better especially in low contention.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95