Is there a way to programmatically get the current jvm stats such as classes loaded or current heap size from C++? I know there are many tools to do so but I would like to integrate this with another application that would read these statistics from time to time.
Asked
Active
Viewed 486 times
2
-
so run from C++ those other tools and collect output? (if you are in normal *NIX world) (not answer, just workaround possible) – Ped7g Jul 25 '16 at 00:18
-
Most of the tools are GUI based with no command line options. They seem to be built in java with swing or something. – LL. Jul 25 '16 at 10:12
-
1[`jstat`](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jstat.html) is a command-line tool for monitoring heap, gc, class loading and JIT compilation. [`jcmd`](https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr006.html) `PerfCounter.print` may also help. – apangin Jul 25 '16 at 11:52
-
within the same process as the JVM or from a different process? – the8472 Jul 25 '16 at 12:45
1 Answers
0
You can have a look at JVMTI and JNI.
JVMTI allows you to attach a native agent to a Java application, with loads of low-level functionalities like heap traversals, etc. It also contains "Garbage Collection Start" & "Garbage Collection Finish" events, which could be used as starting points.
JNI allows you to call Java functions from native code (and vic-versa). I could imagine that you could use this technique to obtain information from ManagementFactory or some similar Java class that provides the needed information. This post contains a complete example on how to call static Java methods via JNI, which should be a good starting point.

Markus Weninger
- 11,931
- 7
- 64
- 137
-
JVMTI agent needs to be loaded by the jvm. It does not seem possible to attach it later on to the jvm. Isn't using java code to get information from the jvm a little silly? You are adding more things for the jvm to load then. You are then intrusively monitoring? – LL. Jul 26 '16 at 14:53
-
@LL.: You may attach a JVMTI agent to a running JVM using `com.sun.tools.attach.VirtualMachine` using tools.jar, have a look here: http://docs.oracle.com/javase/6/docs/jdk/api/attach/spec/com/sun/tools/attach/VirtualMachine.html. The problem is that you need another Java program to attach your native agent to the running JVM, haven't found a solution yet to attach to a JVM directly from native code. – Markus Weninger Jul 27 '16 at 09:50
-
On [one of my own questions](http://stackoverflow.com/questions/38588632/attach-native-application-via-jni-to-already-running-jvm-on-linux), apangin just suggested me his project [jattach](https://github.com/apangin/jattach) which looks promising to attach to a running JVM from native code. – Markus Weninger Jul 27 '16 at 10:00
-
jattach does look promising, but I am not sure about injecting a thread to the jvm though. – LL. Dec 03 '16 at 12:14