Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 248
user496949 Avatar asked Jun 10 '12 09:06

user496949


2 Answers

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.

like image 100
JB Nizet Avatar answered Sep 30 '22 14:09

JB Nizet


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.";
like image 35
Enno Shioji Avatar answered Sep 30 '22 15:09

Enno Shioji