1

If I'm using a ReentrantLock in Java... When a thread has the lock of an object and it tries to acquire another lock of a different object, does it release the first one or does it still hold it?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276

2 Answers2

2

Acquiring a new lock does not release any locks held before. You have to release them explicitly, usually inside a finally block.

But always be careful with acquiring several locks at the same time. Always check that you don't cause deadlocks.

MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44
2

Acquiring a lock does not cause a thread to release any other lock it has already acquired. The API documentation for the Lock interface states that implementations of Lock can hold multiple locks, and uses a technique (hand-over-hand locking) that would not work unless a thread could hold onto more than one lock at a time (emphasis added):

While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, 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.

Since ReentrantLock implements Lock this should be applicable.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276