Javatpoint Logo
Javatpoint Logo

Lock Interface in Java

The lock interface is one of the most used interfaces in Java. Lock interface is available in the Java.util.concurrent.locks package which we use as a thread synchronization mechanism, i.e., similar to synchronized blocks. It is more flexible and provides more options in comparison to the synchronized block.

These are the following differences between synchronized block and lock interface:

Parameter Lock Synchronized block
Guarantee of sequence The lock interface ensures the sequence in which the waiting thread will be given access. Synchronized block doesn't handle it.
No timeout It provides options of timeout when the lock is not granted. It doesn't provide such options.
Single method We can call the lock's method in different methods. It must be fully contained within a single method.

Lock Methods

Lock interface provides the following methods:

1. lock() method

The lock () method is one of the most important methods which is used for acquiring the lock. The current thread will become disabled for thread scheduling purposes when the lock is not available.

The lock () method doesn't return any value and has the following syntax:

2. The lockInterruptibly() method

This method is used to acquire the lock unless the current thread is interrupted. It acquires and returns a lock immediately if it is available. It is also a public method that returns void and takes no parameters:


3. The tryLock() method

It is another important method for acquiring the lock at the time of invocation. It accepts no parameters and returns the lock with a Boolean value based on the availability of the lock.


We use the tryLock() method in the following way:

4. tryLock(long time, TimeUnit unit) method

It is similar to the tryLock() method(without parameter), which immediately returns the lock when the current thread is not interrupted, and the lock will be free within a given waiting time.



It accepts the following two parameters:

time: maximum waiting time for the lock.

unit: time unit of the time argument.

5. The unlock() method

It is a public method used for releasing the lock. It doesn't take any parameter and return any value.


Let's see an example and understand how to implement the Lock interface in Java.


Lock Interface in Java

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA