views:

172

answers:

4

Let us say that one Thread is executing inside a Synchronized Function in Java and another Thread wants to access the same method but it will have to wait till the first Thread completes. How can the second Thread know which Thread is having the Lock on the Object. I would want to print the details of the first Thread and possibly from where the first Thread was initiated.

+1  A: 

If you are using java.util.concurrent.locks.ReentrantLock then a subclass can call getOwner.

Alternatively you can use JMX. Iterate through threads to find the java.lang.management.ThreadInfo with appropriate getLockedMonitors() or getLockedSynchronizers().

Tom Hawtin - tackline
A: 

I believe it is not possible to do that. However you can do something similar with some extra coding:

public void myFunction() {
  System.out.println("" + Thread.currentThread() + " entering sync @ myFunction");
  synchronized(this) {
    System.out.println("" + Thread.currentThread() + " entered sync @ myFunction");

    ...

    System.out.println("" + Thread.currentThread() + " leaving sync @ myFunction");
  }
  System.out.println("" + Thread.currentThread() + " left sync @ myFunction");
}
Zed
A: 

It is a little tricky, almost what Tom Hawtin wrote, but you must explicity request the monitor info when getting the ThreadInfo in dumpAllThreads. Something like:

    Object lock = ...
    ThreadMXBean mx = ManagementFactory.getThreadMXBean();
    ThreadInfo[] allInfo = mx.dumpAllThreads(true, false);
    for (ThreadInfo threadInfo : allInfo) {
        MonitorInfo[] monitors = threadInfo.getLockedMonitors();
        for (MonitorInfo monitorInfo : monitors) {
            if (monitorInfo.getIdentityHashCode() == System.identityHashCode(lock)) {
                StackTraceElement[] stackTrace = threadInfo.getStackTrace();
                // use the the Information from threadInfo
            }
        }
    }
Carlos Heuberger
+1  A: 

Is this for diagnostic purposes, or is it for functionality you want to use as part of your application. If it's for diagnostics, then the various verbose logging solutions in the other answers here are probably enough to get you going. If you want to do this as part of functionality, then you really should use something more robust and flexible than the synchronized keyword, such as the ReentrantLock wizardry mentioned by @Tom.

skaffman