JDK 10: Accessing Java Application’s Process ID from Java
A popular question on StackOverflow.com is, “How can a Java program get its own process ID?” There are several answers associated with that question that include parsing the String
returned by ManagementFactory.getRuntimeMXBean().getName() [but that can provide an “arbitrary string”], using ProcessHandle.getPid() [JEP 102], using Java Native Access (JNA), using System Information Gatherer And Reporter (SIGAR), using JavaSysMon, using Java Native Runtime – POSIX, parsing the results of jps (or jcmd) via invocation of Runtime.getRuntime().exec(String), and other approaches. JDK 10 introduces perhaps the easiest approach of all for obtaining a JVM process’s PID via a new method on the RuntimeMXBean.
JDK-8189091 (“MBean access to the PID”) introduces the RuntimeMXBean method getPid() as a default interface method with JDK 10. That issue states the “Problem” as: “The platform MBean does not provide any API to get the process ID of a running JVM. Some JMX tools rely on the hotspot implementation of RuntimeMXBean::getName which returns < pid >@< hostname >.” The issue also provides the “Solution”: “Introduced new API java.lang.management.RuntimeMXBean.getPid
, so that JMX tools can directly get process ID instead of relying on the implementation detail, RuntimeMXBean#getName().split("@")[0]
.”
The next code listing is a simple one and it demonstrates use of this new getPid()
method on RuntimeMXBean
.
Using JDK 10’s RuntimeMXBean.getPid()
final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); final long pid = runtime.getPid(); final Console console = System.console(); out.println("Process ID is '" + pid + "' Press <ENTER> to continue."); console.readLine();
When the code above is contained within an executable main(String[])
function and that function is executed from the command line, the output is as shown in the next screen snapshot (which also includes a separate terminal used to verify the PID is correct via jcmd).
The process ID is provided as a long
and no parsing of an “arbitrary string” is necessary. This approach also does not require a third-party library or elaborate code to determine the current Java process’s identifier.
This post has provided a brief introduction to what will perhaps be the easiest approach for a Java application (written with JDK 10 or later) to determine its own underlying process ID.
Published on Java Code Geeks with permission by Dustin Marx, partner at our JCG program. See the original article here: JDK 10: Accessing Java Application’s Process ID from Java Opinions expressed by Java Code Geeks contributors are their own. |
This is wonderful