Java Lock Interface

In this tutorial, we will learn about java.util.concurrent.locks.lock interface, types of lock methods with working examples of it including explanation.

java.util.concurrent.locks.lock

In Java, java.util.concurrent.locks.Lock is an interface provides a way to control access of a shared resource in a multi-threaded environment. Assume a lock is like a key to the resource and only one thread can hold that key at a time and access the shared resource and all other threads must wait for the resource until the key or lock is released.

Lock is mechanism of providing exclusive access to a shared resource, only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be obtained first.

Lock Methods:

Lock interface, provides several methods for obtaining lock.

lock(): Acquires the lock if it is not owned or taken by another thread. If the lock is taken by another thread, the current thread waits until the lock is released by the owning thread.

tryLock(): This method provides mechanism to acquire a lock without waiting, if the lock is acquired return true otherwise false at the time of invocation.

tryLock(long time, TimeUnit unit) : This method causes the requesting thread to wait for specified time to obtain the lock, current thread resumes its processing either by getting the lock or wait until specified time whichever comes first.

lockInterruptibly(): This method will wait until the lock gets granted, to interrupt this waiting either lock should be granted or Thread interrupt method should be called any other thread than current thread.

unlock(): Releases the lock of current thread, and this guarantees If more than one thread is waiting to acquire the lock, one of them will get the lock.

Lock interface lock() and unlock() methods example:

In this example, we will use lock() and unlock() methods to achieve lock on the objects.

CopiedCopy Code
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample extends Thread {
	public Locks lock;
	 public LockExample(Locks lock,String threadName) {
		 super(threadName);
		this.lock = lock;
	}
	public static void main(String args[]) {
		Locks locks = new Locks();
		new LockExample(locks,"T1").start();
		new LockExample(locks,"T2").start();
	}
	public void run() {
		this.lock.increment();
		System.out.println("Count Value :"+this.lock.getCount()+" returned by :"+Thread.currentThread().getName());
	}
	static class Locks {
	 private final Lock lock = new ReentrantLock();
	    private int count;
	    public void increment() {
	        lock.lock();
	        try {
	        	System.out.println("Locked by thread :"+Thread.currentThread().getName());
	            count++;
	        } finally {
	        	System.out.println("Locked released by thread :"+Thread.currentThread().getName());
	            lock.unlock();
	        }
	    }
	    public int getCount() {
	        lock.lock();
	        try {
	            return count;
	        } finally {
	            lock.unlock();
	        }
	    }
	}
}

Output :

Locked by thread :T1
Locked released by thread :T1
Count Value :1 returned by :T1
Locked by thread :T2
Locked released by thread :T2
Count Value :2 returned by :T2

Explanation :

In the above example, we have created Locks class which contains data-member as lock. We initialized Locks class in main class and created two threads passed same Locks object. In the run method we tried using the methods Locks class.

In the Locks class all methods can be used by acquiring the lock only, hence only one thread entered in to the methods of Locks class.

In case if you comment out the unlock method in the class, the second thread will wait forever and program will never exit.

Conclusion :

In this tutorial, we have covered what is the Lock interface and its methods with explanation along with the working example of it.