How to check if a Thread holds a lock or not?

There are two ways to find out that “How do you check if a Thread holds a lock or not”

1. To check if a Thread holds a lock or not we can throw IllegalMonitorStateException. The wait() and notify() methods of Object class require that you hold the lock on the object. If you do not hold the lock, then these methods will throw IllegalMonitorStateException in this way you can determine whether you hold the lock or not.

If you call wait() or notify() on an object, without explicitly synchronizing, you will find out whether you held the lock on the object. If you did then the wait() or notify() methods will work and if you did not then IllegalMonitorStateException gets thrown.

2. There is a static method called holdsLock(Object obj) in Thread class which returns true if and only if the current thread holds the monitor lock on the specified object.

Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By :