How to check if given thread holds a lock on given Object

Most of my life I never knew if such method existed, but it does. In Thread class we have a static holdsLock method which can be used to check if the current thread holds the lock of a given object or not

static Object obj = new Object(); static Object obj2 = new Object(); public static void main(String[] args) { func();   } private static void func() { synchronized(obj){ System.out.println(Thread.holdsLock(obj)); System.out.println(Thread.holdsLock(obj2)); }   }

It will print true false

Leave a Reply

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