Lock in Java

Introduction

You may be already aware of basic concepts around thread synchronization and various mechanisms using synchronized keyword. A lock interface is a thread synchronization aid like synchronized block except lock can be used in a more sophisticated way than Java’s synchronized blocks.

A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. Since java.util.concurrent.locks.Lock is an interface, you need to use one of its implementations to use a Lock in your applications. ReentrantLock is one such implementation of Lock interface.

However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.

Related Posts:

Below code snippets show how to use Lock API:

Lock l = ...;
l.lock();
try {
    // access the resource protected by this lock
} finally {
    l.unlock();
}

First an object of Lock is created. Then its lock() method is called. Now the Lock instance is locked. Any other thread calling lock() method will be blocked until the thread that locked the lock calls unlock(). Finally unlock() is called, and the Lock is now unlocked so other threads can lock it. It is recommended to call the lock.unlock() from finally block so that lock is released appropriately when necessary.

Difference between Lock API and synchronized keyword

The main differences between a Lock and a synchronized block are:

  1. Java Lock API provides more visibility and options for locking, unlike synchronized where a thread might end up waiting indefinitely for the lock, you can use tryLock(long timeout, TimeUnit timeUnit) method to make sure thread waits for specific time only.
  2. The synchronized block must be fully contained within a single method whereas you can acquire the lock in one method and release it in another method with Lock API.
  3. Lock interface forces to have try-finally block to make sure Lock is released even if some exception is thrown between lock() and unlock() method calls whereas synchronized block does not have such try-finally block mandate.

Method summary of Lock interface

  • void lock() – acquires the lock.
  • void lockInterruptibly() – acquires the lock unless the current thread is interrupted.
  • Condition newCondition() – returns a new Condition instance that is bound to this Lock instance.
  • boolean tryLock() – acquires the lock only if it is free at the time of invocation.
  • boolean tryLock(long time, TimeUnit unit) – acquires the lock if it is free within the given waiting time and the current thread has not been interrupted.
  • void unlock() – releases the lock.

That’s all about Lock interface in Java.

Leave a Comment