Determining If the Current Thread Is Holding a Synchronized Lock

A thread can determine if it is holding the synchronized lock of a particular object.
public synchronized void myMethod() { boolean hasLock = false; Object o = new Object(); // Determine if current thread has lock for o hasLock = Thread.holdsLock(o); // false synchronized (o) { hasLock = Thread.holdsLock(o); // true } // Check if current thread has lock for current object hasLock = Thread.holdsLock(this); // true }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.