Java.Multithreading.How can I check if a thread holds the monitor of a specific resource?

In Java, there’s no direct API like Thread.holdsMonitor(Object obj) — but there are a few ways to indirectly check or debug whether a thread holds a monitor on a specific object.

✅ 1. Using Thread.holdsLock(Object obj)

This is the most straightforward built-in method:

boolean hasLock = Thread.holdsLock(someObject);

Returns true if the current thread holds the monitor lock on someObject.

Important: Only works for the current thread. You can’t check another thread’s locks this way.

🛠️ 2. Using Thread Dump (for debugging other threads)

If you’re debugging and want to check if some other thread holds a monitor:

  • You can generate a thread dump:
    • In IDE: click on the thread dump tool
    • From terminal: jstack <pid>
  • Look for lines like:
"Thread-1" - waiting to lock <0x00000000> (a java.lang.Object)
   - locked <0x00000000> (a java.lang.Object)

You’ll see which thread holds the lock and which one is waiting.

🧪 3. Using Instrumentation or Profilers

  • Tools like VisualVM, JConsole, or Java Mission Control can help monitor threads and lock ownership in real time.
  • These tools show which thread owns a lock and which threads are waiting for it.

🧵 4. Custom Monitor Tracking (if you really need to track manually)

If you must track lock ownership yourself (not recommended for most cases):

class MonitorWrapper {
    private Thread owner;

    public synchronized void enter() {
        owner = Thread.currentThread();
        // critical section
    }

    public synchronized void exit() {
        // cleanup
        owner = null;
    }

    public synchronized boolean isHeldByCurrentThread() {
        return Thread.currentThread() == owner;
    }

    public synchronized Thread getOwner() {
        return owner;
    }
}

⚠️ But this adds complexity and should be used only if absolutely needed.

🔒 Summary

MethodCan Check Another Thread?Reliable?Notes
Thread.holdsLock(obj)❌ No✅ YesOnly for current thread
Thread dump / jstack✅ Yes✅ YesFor debugging
Java profiling tools✅ Yes✅ YesVisual, great for prod/test
Manual tracking✅ Yes⚠️ RiskyCustom and complex
This entry was posted in Без рубрики. Bookmark the permalink.