Skip to main content

Threads in Java - Reentrant Lock (Part 13)

A Reentrant Lock is nothing but an extension of the synchronized construct with a more controlled locking capability. It is unstructured unlike synchronized i.e. we don't have to use a block structure for locking and can even hold a lock across methods.

private ReentrantLock lock;

// Some code

public void A() {

public void B() {

Clearly, the above flow is impossible to achieve via a single monitor in a synchronized construct.

Synchronized vs Reentrant Lock

In synchronized construct, a thread can take a lock only once and it does not have a mechanism of some waiting queue. So after the exit of one thread, any thread can take the lock. This may cause starvation of resources for some threads.

On the other hand, the ReentrantLock class implements the Lock interface and provides synchronization to methods while accessing shared resources. The locking mechanism is handled by the lock() and the unlock() methods and gives the lock to the current working thread and blocks all other threads.

The ReentrantLock also allows a thread to enter into lock more than once. Each time a thread does that, hold count is incremented by one. And for every unlock request, it is decremented by one. Once the hold count reaches to 0, the resource is unlocked.

Fairness parameter

 The constructor of the ReentrantLock also accepts a fairness parameter, which when set to true, grants access to the longest waiting thread. Using this locks favour granting access to the longest waiting thread. Otherwise, the lock does not guarantee any particular order. 

Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note, however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also, note that the untimed tryLock method does not honour the fairness setting. It will succeed if the lock is available even if other threads are waiting.

Code example

Below code demonstrates the usage of ReentrantLock in action. 

Here, there are two threads t1 and t2 are trying to access the shared getCount() method. The output of the above program will be
Thread-1 gets the count as: 0
Thread-0 gets the count as: 1
Thread-1 gets the count as: 2
Thread-0 gets the count as: 3
Thread-1 gets the count as: 4
Thread-0 gets the count as: 5
As you can see that each thread gets to access the shared getCount() method in synchronization.

Advantages of ReentrantLock

  1. The lock can be accessed in an interruptible fashion
  2. Ability to timeout while waiting for a lock
  3. Can create a fair lock
  4. Ability to try for a lock without waiting


  1. Makes code unreadable because of excessive use of try-finally block
  2. Now programmer is responsible for acquiring and releasing lock which may introduce subtle bugs due to a programmer's error.


Congratulations!! 🙋 today we discussed ReentrantLock class in java with an example and its use cases. I hope you enjoyed this post.

You can find the complete code of this project on my GitHub in this commit. Feel free to fork or open issues, if any.

I would love to hear your thoughts on this and would like have suggestions from you to make it better. 

Feel free to befriend me on FacebookTwitter or Linked In or say Hi by email.

Happy Coding 😊


Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects - making connections caching retrying failed requests threading response parsing error handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from  using the Retrofit library. To work with Retrofit, we need three classes -  Model class to map the JSON data Interfaces which defines the possible HTTP operations Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The respon

Threads in Java - CountDownLatch (Part 12)

A CountDownLatch is a synchronizer which allows one thread to wait for one or more threads before starts processing. A good application of  CountDownLatch is in Java server-side applications where a thread cannot start execution before all the required services are started. Working A  CountDownLatch is initialized with a given count which is the number of threads it should wait for. This count is decremented by calling countDown() method by the threads once they are finished execution. As soon as the count reaches to zero, the waiting task starts running. Code Example Let us say we require three services, LoginService, DatabaseService and CloudService to be started and ready before the application can start handling requests. Output Cloud Service is up! Login Service is up! Database Service is up! All services are up. Now the waiting thread can start execution. Here, we can see that the main thread is waiting for all the three services to start before starting its own

Threads in Java - Masterclass (Part 0)

Threads in Java Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading. One should exploit this feature, especially with all these multiple core machines nowadays. Below are a few reasons why we should use multithreading - 1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a proc