Blog Image

Java Reentrant Lock  

ReentrantLock is the class provided in jdk with some more features than synchronized method. The methods provided to lock the resource by thread and how those methods works is explained as part of this blog. The example showing the use of these  methods are provided as attachment.

 ReentrantLock has been introduced in JDK 1.5. as part of java.util.concurrent.locks package. ReentrantLock behaves like synchronized method but is provided with some more features. When a thread requests for lock for a shared resource, it is permitted only if the resource is not locked by any other thread. If thread does not acquire lock on that resource, it will be blocked until it acquires lock on the resource.
 
 Constructor for reentrant lock:

  • ReentrantLock():Creates an instance of ReentrantLock.
  • ReentrantLock(boolean fair):Creates an instance of ReentrantLock with the given fairness policy.
 ReentrantLock is instantiated using above two constructors i.e. either in fairness mode or unfairness mode. The default is unfairness mode and constructor with true argument creates fairness mode object. Fairness mode means ReentrantLock will be based on the order of lock request and in unfairness mode it does not guarantee the order. Though the throughput of unfairness mode is better in comparison to fairness mode.

 Below are some methods provided by ReentrantLock class:
  • lock(): When lock() called by a thread, the thread will get lock of the resource if the resource is not locked by any other thread. After getting the lock of the resource, immediately the control get returns from lock(). After getting lock on the resource the hold count will be incremented. Every time thread requested for lock on that resource and after successfully getting the lock the hold count will be incremented. If a thread is requested for lock on resource and the resource is locked by other thread then the requesting thread has to wait until it gets the lock.

  • unlock(): If current thread is holding the lock on the resource and called unlock() the hold count is decremented by 1. If the hold count reaches to 0 then thread release the lock on the resource.

  • tryLock(): When the thread calls tryLock() on the resource then if the resource is not locked by any other thread, current thread will acquire the lock on the resource and tryLock() returns true and hold count will be incremented by 1, no matter that other threads are waiting for lock. Even if fairness mode has been set, tryLock() is served first if lock available and otherwise tryLock() returns false and thread does not get blocked.

  • tryLock(long timeout, TimeUnit unit): We can give a waiting time to tryLock() so that it must wait to acquire lock for the given time if resource is locked by other thread. Suppose resource is locked by any thread and current thread calls tryLock(100, TimeUnit.MILLISECONDS) then current thread will wait max for 100 milliseconds to acquire lock on the resource and once other thread which already has lock, unlocks it within 100 milliseconds, the current thread will acquire lock on the resource and hold count will be incremented by one, even if other threads are waiting for lock. If for the specified time, current thread is not able to acquire lock, this method will return false.

  • isHeldByCurrentThread() : This method returns true if lock on the resource is held by current thread otherwise false.

The following example shows the use of lock() and unlock():

public class ReentrantLockDemo {
    final static Lock lock = new ReentrantLock();

    public static void main(String[] args) {

        new Thread(newRunable(), "Thread1").start();
        new Thread(newRunable(), "Thread2").start();
    }

    private static Runnable newRunable() {
        return new Runnable() {

            public void run() {
                lock.lock();
                try {
                    try {
                        System.out.println("locked thread " + Thread.currentThread().getName());
                        Thread.sleep(1000);

                    } finally {
                        lock.unlock();
                        System.out.println("unlocked locked thread " + Thread.currentThread().getName());
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}


The output for the above program is :

locked thread Thread1
unlocked locked thread Thread1
locked thread Thread2
unlocked locked thread Thread2



The following example for use of tryLock():

public class ReentrantLockDemo {
    final static Lock lock = new ReentrantLock();

    public static void main(String[] args) {

        new Thread(newRunable(), "Thread1").start();
        new Thread(newRunable(), "Thread2").start();
    }

    private static Runnable newRunable() {
        return new Runnable() {

            public void run() {

                try {

                    if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
                        try {

                            System.out.println("locked thread " + Thread.currentThread().getName());

                            Thread.sleep(1000);

                        } finally {
                            lock.unlock();
                            System.out.println("unlocked locked thread " + Thread.currentThread().getName());

                        }
                    } else {
                        System.out.println(
                                "unable to lock thread " + Thread.currentThread().getName() + " will re try again");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
    }
}



The output for above program is :

locked thread Thread1
unable to lock thread Thread2 will re try again
unlocked locked thread Thread1


You can download and run the above maven example from the attachments given below.



About author

User Image
AdityaT

I am a software developer. I am working working on jdk , jee technologies. I am working on Spring Framework as well. I am passionate about learning java technologies like Web Services and Restful Services.

0

-Comments

Be the first person to write a comment for this Blog
Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.