user496949
user496949

Reputation: 86075

what the purpose of Thread.holdsLock(lock)?

I saw someone to use assert !Thread.holdsLock(lock) to avoid deadlock.

what's the purpose of this? If the lock object is held by another thread, will assert cause the code to exit immediately?

Upvotes: 6

Views: 3883

Answers (4)

daveT
daveT

Reputation: 11

Deadlocks are a common problem when threads acquire and hold multiple lock at once. A simple way to avoid this problem is to ensure that that multiple locks are always acquired in the same order and release in the same ( reverse ) order. So lock(A) then lock(B). unlock(B) then unlock(A). Seems simple, but these out-of-order lock/unlock issues have a way of sneaking into code.

So before we lock A, ensure that we don't already hold B.

assert !Thread.holdsLock(B)

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

The javadoc of the method says:

Returns true if and only if the current thread holds the monitor lock on the specified object.

(emphasis mine)

So, the assert checks that the current thread does not hold the monitor lock of the given lock object.

Note that asserts are used to check invariants, and can be disabled. They should not be used to prevent deadlock. A regular if test should be used to do that.

Upvotes: 7

Enno Shioji
Enno Shioji

Reputation: 26882

assert keyword is used to capture bugs; it should never be used to control program flow. So either it's a misunderstanding or somebody is doing something very wrong.
More likely, the person put that assert statement there to prevent developers from adding deadlock hazard in that code segment.

Like this:

assert !Thread.holdsLock(lock) : 
"Don't call this method while holding the lock." + 
"This method tries to acquire lock2 and that may cause a deadlock.";

Upvotes: 3

GETah
GETah

Reputation: 21409

The Thread.holdsLock(lock) is only meant to check if the calling thread owns lock, that's it.

It will not prevent deadlocks (would have been so great to have such method :) )

Upvotes: 0

Related Questions