Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find out who create a thread in java?

in tomcat,if a webapp did stop a none daemon thread,tomcat can not be shutdown by shutdown.sh

for example:

public class demo implements ServletContextListener{

  public void contextDestroyed(ServletContextEvent arg0) {
    // TODO Auto-generated method stub
    // yes,we can cancel timer in here,but this is not the major problem
   }

  public void contextInitialized(ServletContextEvent arg0) {        
    Timer timer = new Timer();
    timer.schedule(new Test(), 1000, 1000*10);
    }
}

public class Test extends TimerTask{  
@Override
public void run() {
    System.out.println("AAAA");        
   }
}

like as above,tomcat can not be shutdown by shutdown.sh. from jvisualvm,threads inspector say:

"Timer-0" - Thread t@40
   java.lang.Thread.State: TIMED_WAITING
    at java.lang.Object.wait(Native Method)
    - waiting on <3957edeb> (a java.util.TaskQueue)
    at java.util.TimerThread.mainLoop(Timer.java:552)
    at java.util.TimerThread.run(Timer.java:505)

   Locked ownable synchronizers:
    - None

stack info did not point out which java class created the thread, my question is how to find out who created the thread from many webapps.

Thanks!

like image 700
jenlin Avatar asked Sep 25 '13 08:09

jenlin


1 Answers

Here is the list of approaches, sorted from quickest / most reliable to slowest / hardest:

  1. If you have the source of the class, create an exception in the constructor (without actually throwing it). You can simply examine or print it when you need to know when the thread was created.

  2. If you don't have the sources, the thread name can be a good hint who created it.

  3. If the name hints to a generic service (like java.util.Timer), then you can create a conditional breakpoint in your IDE in the constructor. The condition should be the thread name; the debugger will then stop when someone creates a thread with this name.

  4. If you don't have too many threads, set a breakpoint in the constructors of Thread.

  5. If you have many threads, attach a debugger to the app and freeze it. Then examine the stack traces.

  6. If everything else fails, get the source code for the Java runtime and add logging code in the classes you want to observe, compile a new rt.jar and replace the original one with your version. Don't try this in production, please.

  7. If money isn't an issue, you can use dynamic tracing tools like Compuware APM or, if you're on Linux or Solaris, you can try SystemTap and dtrace, respectively.

like image 180
Aaron Digulla Avatar answered Oct 23 '22 00:10

Aaron Digulla