EN
Java 8 - get current process ID (PID)
5 points
In this short article, we would like to show how to get the current process ID (PID) in Java 8.
There is not a direct method to do it in Java 8, but there is some trick.
Tested on: JRockit, Hotspot JVMs, Corretto.
Practical example:
xxxxxxxxxx
1
import sun.management.VMManagement;
2
import java.lang.management.ManagementFactory;
3
import java.lang.management.RuntimeMXBean;
4
import java.lang.reflect.Field;
5
import java.lang.reflect.Method;
6
7
public class Program {
8
9
private static int getCurrentProcessId() throws Exception {
10
11
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
12
Field jvm = runtime.getClass().getDeclaredField("jvm");
13
jvm.setAccessible(true);
14
15
VMManagement management = (VMManagement) jvm.get(runtime);
16
Method method = management.getClass().getDeclaredMethod("getProcessId");
17
method.setAccessible(true);
18
19
return (Integer) method.invoke(management);
20
}
21
22
public static void main(String[] args) throws Exception {
23
24
System.out.println("PID: " + getCurrentProcessId());
25
}
26
}
Example output:
xxxxxxxxxx
1
PID: 7788