0

I am willing to run another jar file and get its threads, so I thought running the jar this way will run the jar on the current JVM:

Process p = Runtime.getRuntime().exec("java -jar " + path);

And then to get the threads like this:

ThreadGroup rootThreadGroup = null;

ThreadGroup getRootThreadGroup( ) {
    if ( rootThreadGroup != null )
        return rootThreadGroup;
    ThreadGroup tg = Thread.currentThread( ).getThreadGroup( );
    ThreadGroup ptg;
    while ( (ptg = tg.getParent( )) != null )
        tg = ptg;
    return tg;
}

Thread[] getAllThreads( ) {
    final ThreadGroup root = getRootThreadGroup( );
    final ThreadMXBean thbean = ManagementFactory.getThreadMXBean( );
    int nAlloc = thbean.getThreadCount( );
    int n = 0;
    Thread[] threads;
    do {
        nAlloc *= 2;
        threads = new Thread[ nAlloc ];
        n = root.enumerate( threads, true );
    } while ( n == nAlloc );
    return java.util.Arrays.copyOf( threads, n );
}

But it is not showing the new jar threads I ran before, even though I put a Thread.sleep(4000); line to wait a little bit.
Isn't that suppose to get all the threads running in JVM?
code source

Tarek
  • 1,754
  • 2
  • 17
  • 35
  • Is the code you pasted in second code group running in a separate process? If so, you won't see the other processes threads. To get threads if you're running in same jvm instance see: http://stackoverflow.com/questions/1323408/get-a-list-of-all-threads-currently-running-in-java Or, if you're outside process, you can do something like: http://stackoverflow.com/questions/407612/how-to-get-a-thread-and-heap-dump-of-a-java-process-on-windows-thats-not-runnin – Grady G Cooper May 09 '15 at 03:42
  • "I thought running the jar this way will run the jar on the current JVM" - No, running the jar this way will run it in a new JVM, not in the current one. – Erwin Bolwidt May 09 '15 at 03:56
  • Runtime.exec invokes the command on the underlying operating system not in the current JVM. – redge May 09 '15 at 04:01
  • @GradyGCooper I want to do it regarding the fact that each process has its own threads. – Tarek May 09 '15 at 04:05
  • @ErwinBolwidt well, that is new. I think I must search more for the way to run it on the current JVM. If you know how give me a hint please. – Tarek May 09 '15 at 04:05
  • @redge but eventually, it is running on some JVM, I thought there is one JVM that runs all the jar files. But it seems that was wrong. Can you please give some hints to run it correctly? By correctly I mean on the same JVM. – Tarek May 09 '15 at 04:08
  • See http://stackoverflow.com/questions/18394560/when-multiple-java-programs-run-on-the-same-machine – Grady G Cooper May 09 '15 at 04:12
  • Make the method public, add the jar to your classspath and call it directly – redge May 09 '15 at 04:13

0 Answers0