Reentrant lock

  • Eclipse: Oxygen
  • Java: 1.8

The Reentrant lock is a mutually exclusive lock. This lock means that the lock can be accessed by the thread that owns it or controls it more than once. Therefore, if any thread has access to that lock, no other thread, except that thread, can use that. This is the specific use of that lock.

Here we show how to use ReentrantLock in Java. Reentrant locking is an alternative form of locking apart from the implicit locking provided by keyword synchronized in Java.

In the following program, we create a ReentrantLock object. In the main method, we create two threads to execute and pass the lock to the object. Use the lock () method to acquire the lock on the shared resource. After completing the job, call the unlock() method to release the lock.

Output

The final value of counter is 2000

A finally block contains all the crucial declarations that must be executed, whether an exception occurs or not. The declarations present in this block will always be executed regardless of whether an exception occurs in the try block or not.

It is optional, a try-catch block is sufficient for exception handling, however, if you place a finally block then it will always run after the execution of try block.

Suppose that within for loop we find an exception in that type of scenario lock will not be released because we will not be able to call the lock.unlock () method. In that situation, we will use finally block.

 

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu