javajava-threadshypericmxbean

How to list all threads of the host OS from within a Java VM?


Is there some API in the Java standard library with which from within a JVM some Java code can be executed that lists all OS threads of the host OS the JVM is running on?

In particular, I don't want to list all the Java threads of the JVM that executes my Java code, but a list of the OS threads of the host OS of which the host process running the JVM is just one of the OS threads. So I want a list of OS threads analoguously to what the Linux top command would show by running Java code.

At best have a way that from within Java the OS thread id can be queried that runs the JVM in which the Java code is executed to list all those OS threads. Would be needed for some load balancing I would like to implement for Java.

UPDATE:

In the meanwhile I found hyperic sigar which calls libraries written for Windows and Linux. Unhappily it crashes on me and seems to be discontinued.

Being on Windows I do load the Sigar Windows DLL. Calling "System.loadLibrary" works for me (crashed till I got it working):

static {
        System.loadLibrary("sigar-amd64-winnt");
}

But running code from the sigar.jar causes stack dumps:

public static void main(String[] args) throws SigarException {
    var sigar = new Sigar();
    var list = sigar.getCpuList();
    for(var cpu : list) {
        System.out.println(cpu);
    }
}

But then executing "sigar.getCpuList()" causes a crash:

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) j org.hyperic.sigar.Sigar.getCpuListNative()[Lorg/hyperic/sigar/Cpu;+0 j org.hyperic.sigar.Sigar.getCpuList()[Lorg/hyperic/sigar/Cpu;+1 j org.objectscape.Scratch.main([Ljava/lang/String;)V+9 v ~StubRoutines::call_stub

It seems that the Windows dll does not work any more for newer JDKs.

Think there was a way to list all OS threads of the OS some JVM is running on which was added in a newer JDK. Just can't remember it and can find it any more searching the Internet ...


Solution

  • Think I now found a way to do it by calling ManagementFactory.getOperatingSystemMXBean() to get a OperatingSystemMXBean, and casting to a OperatingSystemMXBean (same name, confusingly).

    var operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) 
    ManagementFactory.getOperatingSystemMXBean(); 
    System.out.println(operatingSystemMXBean.getSystemCpuLoad());
    

    The CPU load percentage printed to the console is about within a certain range what Windows task manager is showing. So the value seems to be meaningful enough for my purposes.