11

While working on IntelliJ , I am unable to check that if the thread is holding the lock or not.

On eclipse GUI there is a lock like icon against the thread , telling us that it is holding that lock.

In below code snapshot, my thread is at notifyElementAdded() and holding the lock however, in a thread stack there is no such Icon or intimation from Intellij

So my question is how to check the same on IntelliJ GUI.

enter image description here

T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 1
    Perhaps worth requesting a new feature from Jetbrains https://youtrack.jetbrains.com/issues/IDEA?q=thread%20holding%20lock – nabster May 11 '20 at 03:50

4 Answers4

4

There is actually a boolean attribute to the Thread class in Java - Thread.holdsLock(). To get the name of the thread which holds the monitor you can use the code example below:

public static long getMonitorOwner(Object obj)
{
    if (Thread.holdsLock(obj)) 
    {
        return Thread.currentThread().getId();
    }
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Foivoschr
  • 455
  • 1
  • 4
  • 14
2

I don't think there is a similar functionality. But you can still check by getting the dump

Get Thread Dump

You can click on Get Thread Dump in Debug window and then you can see the locked in the log to see that the thread is actually holding the lock

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
2

Create a custom variable in the Intellij debugging console using the plus button as shown in the image below.

Now every time you run the code in the debug mode, this variable will be re-calculated at your all debug points.

I created a variable- Thread.holdsLock(AwsS3ClientHelper.class) since I was acquiring a lock on the class itself. You can write any variable of your choice there. In your particular case, it will be Thread.holdsLock(observers).

enter image description here

Mukul Bansal
  • 878
  • 8
  • 10
0

This can be a potential feature request for IntelliJ to include this to their GUI product.

Programmatically, to verify this you can use the java.lang.Thread.holdsLock() method which returns true if and only if the current thread holds the monitor lock on the specified object

public static boolean holdsLock(Object obj)

Below snippet of run method for reference,

public void run() {

   /* returns true if thread holds monitor lock */

   // returns false
   System.out.println("Holds Lock = " + Thread.holdsLock(this));  

   synchronized (this) {
      // returns true
      System.out.println("Holds Lock = " + Thread.holdsLock(this));
   }
 }
Vignesh T I
  • 782
  • 1
  • 7
  • 22