Java Concurrency - Lock Objects (java.util.concurrent.locks)


Lock Object package is a High Level Concurrency of the java.util.concurrent. For low-level, intrinsic lock (monitor), see Java Concurrency - Monitor (Intrinsic|Implicit) Lock.

There is interfaces and classes that provide a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.


  • As with implicit locks, only one thread can own a Lock object at a time.
  • Lock objects also support a wait/notify mechanism, through their associated Condition objects.


Back out

The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock.

The tryLock method backs out:

  • if the lock is not available immediately
  • or before a timeout expires (if specified).

The lockInterruptibly method backs out:

  • if another thread sends an interrupt before the lock is acquired.

“hand-over-hand” or “chain locking”

The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released

  • in the opposite order,
  • in the same lexical scope in which they were acquired.

There are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of “hand-over-hand” or “chain locking”: you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

Powered by ComboStrap