Is there a way to tell, for a Java object, which Thread (or null) currently owns its monitor? Or at least a way to tell if the current thread owns it?
I've found out some answers myself. To test if the current thread holds the monitor, Thread.holdsLock
exists!
if (!Thread.holdsLock(data)) {
throw new RuntimeException(); // complain
}
This is really fast (sub-microsecond) and has been available since 1.4.
To test in general, which thread (or thread ID) holds the lock, it's possible to do this with java.lang.management
classes (thanks @amicngh).
public static long getMonitorOwner(Object obj) {
if (Thread.holdsLock(obj)) return Thread.currentThread().getId();
for (java.lang.management.ThreadInfo ti :
java.lang.management.ManagementFactory.getThreadMXBean()
.dumpAllThreads(true, false)) {
for (java.lang.management.MonitorInfo mi : ti.getLockedMonitors()) {
if (mi.getIdentityHashCode() == System.identityHashCode(obj)) {
return ti.getThreadId();
}
}
}
return 0;
}
There's a few caveats with this:
ThreadMXBean.isObjectMonitorUsageSupported()
is true, so it's less portable.But if you only want to test the current thread, Thread.holdsLock
works great! Otherwise, implementations of java.util.concurrent.locks.Lock
may provide more information and flexibility than ordinary Java monitors (thanks @user1252434).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With