Object obj = new Object(); synchronized(obj) { if (Thread.holdsLock(obj)) { System.out.println("Thread owns the monitor of obj"); } }
class MyClass { public synchronized void method1() { if (Thread.holdsLock(this)) { System.out.println("Thread owns the monitor of this object"); } } }In this example, we have a class with a synchronized method. We then use the holdsLock() method to check whether the current thread owns the monitor of the object on which the method is being executed. Since the method is synchronized, the thread should hold the lock. This method is also part of the java.lang.Thread class.