How can a Java program get its own process ID?

后端 未结 22 2052
梦毁少年i
梦毁少年i 2020-11-22 03:47

How do I get the id of my Java process?

I know there are several platform-dependent hacks, but I would prefer a more generic solution.

22条回答
  •  遇见更好的自我
    2020-11-22 04:15

    For completeness there is a wrapper in Spring Boot for the

    String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    return jvmName.split("@")[0];
    

    solution. If an integer is required, then this can be summed up to the one-liner:

    int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
    

    If someone uses Spring boot already, she/he might use org.springframework.boot.ApplicationPid

    ApplicationPid pid = new ApplicationPid();
    pid.toString();
    

    The toString() method prints the pid or '???'.

    Caveats using the ManagementFactory are discussed in other answers already.

提交回复
热议问题