Determining If the Current Thread Is Holding a Synchronized Lock - Java Thread

Java examples for Thread:Thread Operation

Description

Determining If the Current Thread Is Holding a Synchronized Lock

Demo Code


public class Main {
  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
    }//w ww  . j  a  va 2s .  co  m

    // Check if current thread has lock for current object
    hasLock = Thread.holdsLock(this); // true
  }
}

Related Tutorials