Monday 21 March 2016

Reentrant locks vs Synchronized methods

Almost every java developer knows about synchronizing methods or code blocks using synchronized keyword, but very few knows abut synchronizing using Reentrant locks.

Before moving on to code samples directly, I would strongly suggest you to read the java doc for Reentrant lock :

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

You will be already impressed by the number of utility methods provided by the lock, and how it helps in making a multi threaded application development easier.

Now lets move on to one of the simplest use case of using re-entrant lock , ie, implementing synchronized methods using re entrant locks.

This is how a synchronized method looks like :


 private void synchronized setValue(int myValue) {
        //setting a value for concurrent hashset
        value = value + myValue;
 }

The same can be achieved using a re-entrantlock as follows :

//define a reentrant lock as follows : 
final Lock valueLock = new ReentrantLock();

private void setValue(int myValue) {
        try {
            if (valueLock .tryLock(10, TimeUnit.SECONDS)) {
               value = value + myValue;  
            }
        } catch (InterruptedException e) {
            log.error("Exception while acquiring the lock!! ");
        } finally {
            valueLock .unlock();
        }
    }


Benefits of this approach :

We as developers receive more flexibility with locks . We can determine the time a thread has to wait for locks, we can even design a lock that follows fairness policy, and thus be impartial towards any thread. Developers get more control over the lock, which is an added advantage