Calling jcmd Commands Programmatically

JCmd allows you to quickly get information on an existing JVM. This helpful for getting things like thread-dumps (see jstall for tool that heavily relies on this). In this blog post you’ll learn to send JCmd diagnostic commands programmatically. You can find the whole code of this blog post on GitHub.

Let’s get a sample application running:

> java Loop.java &
[1] 23462

Now we want to obtain the VM arguments and the Java command, that’s easy on the command line via jcmd:

> jcmd 23462 VM.command_line
23462:
VM Arguments:
jvm_args: --add-modules=ALL-DEFAULT 
java_command: jdk.compiler/com.sun.tools.javac.launcher.SourceLauncher Loop.java
java_class_path (initial): .
Launcher Type: SUN_STANDARD

But how can we do it programmatically? Calling jcmd always starts a new JVM, which we might not want.

This is where the Diagnostic MBean comes into play.

Continue reading