What is the purpose of Thread.holdsLock (lock)?

I saw someone use assert !Thread.holdsLock(lock)to avoid a dead end.

What is the purpose of this? If the lock object is held by another thread, will it claim that the code will immediately exit the system?

+5
source share
3 answers

The javadoc method says:

Returns trueif and only if the current stream holds the monitor lock on the specified object.

(emphasis mine)

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

, . . if.

+6

assert ; . , - - .
, assert, .

:

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.";
+3

Thread.holdsLock(lock) , lock, .

( :))

0

All Articles