Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Java program get its own process ID?

Tags:

java

pid

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.

like image 638
Dmitry Shechtman Avatar asked Aug 30 '08 09:08

Dmitry Shechtman


People also ask

How can a Java program gets its own process ID?

getRuntimeMXBean(). getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use. On linux+windows it returns a value like "12345@hostname" ( 12345 being the process id).

How do I find program process ID?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column.

How can I get the process ID of Java application in Linux?

On Linux, you can view processes with the ps command. It is the simplest way to view the running processes on your system. You can use the ps command to view running Java processes on a system also by piping output to grep .


1 Answers

There exists no platform-independent way that can be guaranteed to work in all jvm implementations. ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use.

On linux+windows it returns a value like "12345@hostname" (12345 being the process id). Beware though that according to the docs, there are no guarantees about this value:

Returns the name representing the running Java virtual machine. The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string. Each running virtual machine could have a different name.

In Java 9 the new process API can be used:

long pid = ProcessHandle.current().pid(); 
like image 159
Wouter Coekaerts Avatar answered Oct 02 '22 14:10

Wouter Coekaerts