lock Interface in Java

lock object is similar to an implicit lock acquired by a thread to execute a synchronized method or Synchronized block.

java.util.concurrent.locks.Lock

lock Interface provides more extensive operations than traditional implicit locks –

Important Method of lock Interface

  • void lock()

We can use this method to acquire a lock. If the lock is available, the current thread will get the lock immediately; if the lock is not available, it will wait until getting the lock. It is the same behavior as the traditional Synchronized Keyword

  • boolean tryLock()

This method is used to acquire the lock without waiting. If the lock is available then Thread will acquire that lock and return true and if the lock is not available then it returns false, and Thread will continue its execution without waiting. In this case, Thread will never enter into the waiting state.

  • boolean tryLock(long time, TimeUnit unit)

By using this method if the lock is available then the Thread will get the lock and continue its execution. If the lock is not available then Thread will wait for a specified time, still if the lock is not available the thread can continue its execution.

  • void lockInterruptibly()

This method acquires the lock if it is available and returns immediately. If the lock is not available then it will wait and while waiting if the thread is interrupted then the thread would not get the lock.

  • void unlock()

To call this method it is compulsory that the current thread should be the owner of the lock otherwise we will get RunTimeException.

Similar Java Tutorials

Leave a Comment