Java — java.util.concurrent.locks.Lock Interface | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

  • Lock object is similar to implicit lock aquired by a thread to execute synchronized method or synchronized block.

Important methods of Lock interface :

1. void lock()

  • We can use this method to aquired a lock. If lock is already available then immediately current thread will get that lock. If the lock is not already available then it will wait until getting a lock. It is exactly same behaviour of traditional synchronized keyword.

2. boolean tryLock()

  • To aquire the lock without waiting
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}

3. boolean tryLock(long time, TimeUnit unit) throws InterruptedException

  • If lock is available then the thread will get the lock and continue it’s execution.
l.tryLock(1, TimeUnit.HOURS)

TimeUnit :

  • TimeUnit is an enum present in java.util.concurrent.
public enum TimeUnit {
NANOSECONDS,
MICROSECONDS,
MILLISECONDS,
SECONDS,
MINUTES,
HOURS,
DAYS
}

4. void lockInterruptibly() throws InterruptedException

  • Aquire the lock if it is available and returns immediately.

5. void unlock()

  • To release a lock.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store