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

  • Lock object is similar to implicit lock aquired by a thread to execute synchronized method or synchronized block.
  • Lock implementation provide more extensive operations then traditional implicit locks.
  • 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.
  • To aquire the lock without waiting
  • If lock is available then the thread acquire that lock and returns true and if the lock is not available then this method returns false and can contain it’s execution without waiting. In this case thread never be entered into waiting state.
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
  • If lock is available then the thread will get the lock and continue it’s execution.
  • If lock is not available then the thread will wait until specified amount of time. Still if the lock is not available then thread can continue it’s execution.
l.tryLock(1, TimeUnit.HOURS)
  • TimeUnit is an enum present in java.util.concurrent.
public enum TimeUnit {
NANOSECONDS,
MICROSECONDS,
MILLISECONDS,
SECONDS,
MINUTES,
HOURS,
DAYS
}
  • Aquire the lock if it is available and returns immediately.
  • If lock is not available then it will wait.
  • While waiting if the thread is interrupted then thread wouldn’t get the lock.
  • To release a lock.
  • To call this method compulsory current thread shouls be owner of the lock otherwise we RE IllegalMonitorStateException.

--

--

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