Finding running instances in a running JVM

人盡茶涼 提交于 2019-12-03 16:42:50

You can indeed get a stack trace of all running Threads dumped to the stdout by using kill -QUIT <pid> on a *NIX like OS, or by running the application in a Windows console and pressing Ctrl-Pause (as another poster notes.)

However, it seems like you're asking for programmatic ways to do it. So, assuming what you really want is the set of all Threads who's current call stacks include one or more methods from a given class...

The best thing I can find that doesn't involve calls into the JVMTI is to inspect the stacks of all running threads. I haven't tried this, but it should work in Java 1.5 and later. Keep in mind that this is, by definition, not AT ALL thread-safe (the list of running threads - and their current stack traces - are going to constantly change underneath you...lots of paranoid stuff would be necessary to actually make use of this list.)

public Set<Thread> findThreadsRunningClass(Class classToFindRunning) {

  Set<Thread> runningThreads = new HashSet<Thread>();
  String className = classToFindRunning.getName();

  Map<Thread,StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
  for(Thread t : stackTraces.keySey()) {
    StackTraceElement[] steArray = stackTraces.get(t);
    for(int i = 0;i<steArray.size();i++) {
      StackTraceElement ste = steArray[i];
      if(ste.getClassName().equals(className)) {
        runningThreads.add(t);
        continue;
      }
    }
  }

  return runningThreads;
}

Let me know if this approach works out for you!

From this page,

A Java profiler uses a native interface to the JVM (the JVMPI for Java <=1.4.2 or the JVMTI for Java >=1.5.0) to get profiling information from a running Java application.

This amounts to some Sun supplied native code that gives a profiler hooks into the JVM.

If you only need a quick stack trace of your running application to find out which threads are blocking the JVM exit, you can send it the QUIT signal.

$ kill -QUIT <pid of java process>

Under Windows you need to run the application in a console window (using java.exe, not javaw.exe), then you can press Ctrl-Pause to generate the stack dump. In both cases it’s written to stdout.

Mark

I use Visual VM to monitor the JVM. Has lots of features, give it a try.

I think you need a Java thread dump. This should list all threads with what they are doing at the moment. I had a similar problem myself, which a thread dump helped solve (Quartz scheduler threads, which did not exit when Tomcat finished).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!