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?
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.
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.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With