Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracking Java thread creation and lifetime

Are there any tools available to track the creation and lifetime of Java threads? I would be interested in all of the following:

  • The call stack which called new Thread()
  • The call stack which called start()
  • The lifetime of the run() method
like image 630
mchr Avatar asked Mar 26 '12 15:03

mchr


2 Answers

I have written and published an open source tool to answer this question.

Java Live Thread Analyser

I have blogged about the tool here.

like image 156
mchr Avatar answered Oct 22 '22 12:10

mchr


I don't know of any framework like this. You certainly could subclass the Thread class and store this information on your own like the following. This however will not track Threads that are allocated in other classes such as Executors, etc..

  public class MyThread extends Thread {
      StackTraceElement[] constructorTrace;
      StackTraceElement[] startTrace;
      long runStartTimeMillis;
      long runFinishTimeMillis;

      // you'll need to duplicate the constructors you need
      public MyThread() {
         super();
         constructorTrace = Thread.currentThread().getStacktrace();
      }

      @Override
      public void start() {
         super.start();
         startTrace = Thread.currentThread().getStacktrace();
      }

      @Override
      public void run() {
         runStartTimeMillis = System.currentTimeMillis();
         super.run();
         runFinishTimeMillis = System.currentTimeMillis();
      }
  }
like image 43
Gray Avatar answered Oct 22 '22 10:10

Gray