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


Index Page : Link

Donate : Link

Medium Link : Link

Applications : Link

  • 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.

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
  • 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
 }

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.
  • 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 :

  • 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.
  • If lock is not available then it will wait.
  • While waiting if the thread is interrupted then thread wouldn’t get the lock.

5. void unlock()

  • To release a lock.
  • To call this method compulsory current thread should be owner of the lock otherwise we will get RE: IllegalMonitorStateException.

4 thoughts on “Java – java.util.concurrent.locks.Lock Interface | Code Factory”

  1. Greetings from Florida! I’m bored at work so I decided to check out your blog on my iphone during lunch break. I really like the information you provide here and can’t wait to take a look when I get home. I’m shocked at how quick your blog loaded on my phone .. I’m not even using WIFI, just 3G .. Anyhow, excellent blog!

    Liked by 1 person

Leave a comment