Thursday, March 7, 2013

ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock

ReentrantLock in Java is added on java.util.concurrent package in Java 1.5 along with other concurrent utilities like CountDownLatch, Executors and CyclicBarrier. ReentrantLock is one of the most useful addition in Java concurrency package and several of concurrent collection classes from java.util.concurrent package is written using ReentrantLock, including ConcurrentHashMap, see How ConcurrentHashMap works in Java for more details. Two key feature of ReentrantLock, which provides more control on lock acquisition is trying to get a lock with ability to interrupt, and a timeout on waiting for lock, these are key for writing responsive and scalable systems in Java. In short, ReentrantLock extends functionality of synchronized keyword in Java and open path for more controlled locking in Java. 

In this Java concurrency tutorial we will learn :
  • What is ReentrantLock in Java ?
  • Difference between ReentrantLock and synchronized keyword in Java?
  • Benefits of using Reentrant lock in Java?
  • Drawbacks of using Reentrant lock in concurrent program?
  • Code Example of ReentrantLock in Java?


What is ReentrantLock in Java

On class level,  ReentrantLock is a concrete implementation of Lock interface provided in Java concurrency package from Java 1.5 onwards.  As per Javadoc, ReentrantLock is mutual exclusive lock, similar to implicit locking provided by synchronized keyword in Java, with extended feature like fairness, which can be used to provide lock to longest waiting thread. Lock is acquired by lock() method and held by Thread until a call to unlock() method. Fairness  parameter is provided while creating instance of ReentrantLock in constructor. ReentrantLock provides same visibility and ordering guarantee, provided by implicitly locking, which means, unlock() happens before another thread get lock().


Difference between ReentrantLock and synchronized keyword in Java

Though ReentrantLock provides same visibility and orderings guaranteed as implicit lock, acquired by synchronized keyword in Java, it provides more functionality and differ in certain aspect. As stated earlier,  main difference between synchronized and ReentrantLock is ability to trying for lock interruptibly, and with timeout. Thread doesn’t need to block infinitely, which was the case with synchronized. Let’s see few more differences between synchronized and Lock in Java.

1) Another significant difference between ReentrantLock and synchronized keyword is fairness. synchronized keyword doesn't support fairness. Any thread can acquire lock once released, no preference can be specified, on the other hand you can make ReentrantLock fair by specifying fairness property, while creating instance of ReentrantLock. Fairness property provides lock to longest waiting thread, in case of contention.

2) Second difference between synchronized and Reentrant lock is tryLock() method. ReentrantLock provides convenient tryLock() method, which acquires lock only if its available or not held by any other thread. This reduce blocking of thread waiting for lock in Java application.

3) One more worth noting difference between ReentrantLock and synchronized keyword in Java is, ability to interrupt Thread while waiting for Lock. In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock. Similarly tryLock() with timeout can be used to timeout if lock is not available in certain time period.

4) ReentrantLock also provides convenient method to get List of all threads waiting for lock.

So, you can see, lot of significant differences between synchronized keyword and ReentrantLock in Java. In short, Lock interface adds lot of power and flexibility and allows some control over lock acquisition process, which can be leveraged to write highly scalable systems in Java.

Benefits of ReentrantLock in Java

ReentrantLock in Java with example and difference between synchronized keyword
Most of the benefits derives from the differences covered between synchronized vs ReentrantLock in last section. Here is summary of benefits offered by ReentrantLock over synchronized in Java:

1) Ability to lock interruptibly.
2) Ability to timeout while waiting for lock.
3) Power to create fair lock.
4) API to get list of waiting thread for lock.
5) Flexibility to try for lock without blocking.

Disadvantages of ReentrantLock in Java

Major drawback of using ReentrantLock in Java is wrapping method body inside try-finally block, which makes code unreadable and hides business logic. It’s really cluttered and I hate it most, though IDE like Eclipse and Netbeans can add those try catch block for you. Another disadvantage is that, now programmer is responsible for acquiring and releasing lock, which is a power but also opens gate for new subtle bugs, when programmer forget to release the lock in finally block.

Lock and ReentrantLock Example in Java

Here is a complete code example of How to use Lock interface and ReentrantLock in Java. This program locks a method called getCount(), which provides unique count to each caller. Here we will see both synchronized and ReentrantLock version of same program. You can see code with synchronized is more readable but it’s not as flexible as locking mechanism provided by Lock interface.

import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to show, how to use ReentrantLock in Java.
 * Reentrant lock is an alternative way of locking
 * apart from implicit locking provided by synchronized keyword in Java.
 *
 * @author  Javin Paul
 */
public class ReentrantLockHowto {

    private final ReentrantLock lock = new ReentrantLock();
    private int count = 0;

     //Locking using Lock and ReentrantLock
     public int getCount() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " gets Count: " + count);
            return count++;
        } finally {
            lock.unlock();
        }
     }

     //Implicit locking using synchronized keyword
     public synchronized int getCountTwo() {
            return count++;
     }

    

    public static void main(String args[]) {
        final ThreadTest counter = new ThreadTest();
        Thread t1 = new Thread() {

            @Override
            public void run() {
                while (counter.getCount() < 6) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();                    }
                }
            }
        };
      
        Thread t2 = new Thread() {

            @Override
            public void run() {
                while (counter.getCount() < 6) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };
      
        t1.start();
        t2.start();
      
    }
}

Output:
Thread-0 gets Count: 0
Thread-1 gets Count: 1
Thread-1 gets Count: 2
Thread-0 gets Count: 3
Thread-1 gets Count: 4
Thread-0 gets Count: 5
Thread-0 gets Count: 6
Thread-1 gets Count: 7

That’s all on What is ReentrantLock in Java, How to use with simple example, and difference between ReentrantLock and synchronized keyword in Java. We have also seen significant enhancement provided by Lock interface over synchronized e.g. trying for lock, timeout while waiting for lock and ability to interrupt thread while waiting for lock. Just be careful to release lock in finally block.

Related Java multithreading and concurrency tutorials from Javarevisited Blog

8 comments :

SARAL SAXENA said...

Javin please edit the program I think you have missed to put the synchronized keyword ..it should be ..

//Implicit locking using synchronized keyword
public int synchronized getCountTwo() {
return count++;
}


SARAL SAXENA said...

Reentrant lock functionality :-
============================

A reentrant lock will allow the lock holder to enter blocks of code even after it has already obtained the lock by entering other blocks of code. A non-reentrant lock would have the lock holder block on itself as it would have to release the lock it obtained from another block of code to reobtain that same lock to enter the nested lock requiring block of code

public synchronized void functionOne() {

// do something

functionTwo();

// do something else

// redundant, but permitted...
synchronized(this) {
// do more stuff
}
}

public synchronized void functionTwo() {
// do even more stuff!
}



Extended capabilities of reentrant lock include :-
===============================================

1) The ability to have more than one condition variable per monitor. Monitors that use the synchronized keyword can only have one. This means reentrant locks support more than one wait()/notify() queue.
2) The ability to make the lock "fair". "[fair] locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order." Synchronized blocks are unfair.
3) The ability to check if the lock is being held.
4) The ability to get the list of threads waiting on the lock.


Disadvantages of reentrant locks are :-
====================================

Need to add import statement.
Need to wrap lock acquisitions in a try/finally block. This makes it more ugly than the synchronized keyword.
The synchronized keyword can be put in method definitions which avoids the need for a block which reduces nesting.


When to use :-
===========

1. ReentrantLock might be more apt to use if you need to implement a thread that traverses a linked list, locking the next node and then unlocking the current node.
2. Synchronized keyword is apt in situation such as lock coarsening, provides adaptive spinning,biased locking and the potential for lock elision via escape analysis. Those optimizations aren't currently implemented for ReentrantLock.

Javin @ BlockingQueue in Java said...

@Saral, great comment. In context of allowing thread to reenter to a block of code, which is also locked by same lock, implicit locking by synchronized keyword also provides same functionality. In short, implicit lock is also re-entrant. I think, ReentrantLock should be prefer over synchronized for high performance code, you can see almost all classes on java.util.concurrent uses ReentrantLock.

JackTheR said...

I guess most important difference between a synchronized lock and a ReentrantLock is to release lock in a different code block. With ReentrantLock, you can acquire lock in one method and can release in other method, but synchronized keyword forces you to release lock in same code block, doesn't matter if you synchronized method or block.

Anonymous said...

I ran few example with almost 50 threads kicking at same time (also No sleep call on thread ) using reentarant lock and found that thread were still entering in block though other thread already already acquired a lock. Problem resolved when i create the reentrant object as static final (private static final ReentrantLock rLock = new ReentrantLock()) .

Gaurav Agarwal said...

public class RentractLockHowTo extends Thread{

private static final ReentrantLock lock =new ReentrantLock();
int counter =0;;
@Override
public void run(){

try{
lock.tryLock();
System.out.println(Thread.currentThread().getName());
System.out.println(counter++);

}finally{
//lock.unlock();
}
}

public static void main(String[] args) throws Exception{

RentractLockHowTo tes = new RentractLockHowTo();
Thread t1= new Thread(tes);
Thread t2 = new Thread(tes);
RentractLockHowTo t = new RentractLockHowTo();
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
Thread t5 = new Thread(t);

t1.start();

t2.start();
//Thread.sleep(1000);
t3.start();
t4.start();
t5.start();
}

I wrote this class.But when i put a debug Point at lock.tryLock(),allthe 6 threads entered at the same time in the tryLock block.Can u tell me why this happens that all the 6 locks are entered into the Lock block .

Anonymous said...

public void run() {

try {
lock.lock();//<-----

System.out.println(Thread.currentThread().getName());
System.out.println(counter++);

} finally {
lock.unlock();
}
}

Neetu Pal said...

Hi Javin,
i have a doubt regarding your code written below.

Thread t1 = new Thread() {

@Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace(); }
}
}
};

can wr write a single run() method for both the threads..? i tried to to that by creating a new class extending Thread class and override the run() method same as above but out put is not coming same. i mean count value is repeating for thread 1 and thread 2. please Explain....

Post a Comment