List of Java Processes

Java code - Best way to list java processes in localhost JVM (for Linux & Windows]

I finally found the 3rd party library named Oshi, which apparently does not need JDK and is compatible with Java 1.8: https://github.com/oshi/oshi

For future reference, here is a sample method:

public static List<OSProcess> getOSProcesses() {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
return os.getProcesses();
}

How to find the process id of a running Java process on Windows? And how to kill the process alone?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.

Then use the Windows task manager to terminate the process. If you want to do it on the command line, use

TASKKILL /PID %PID%

How to get a list of running processes in Java and check if a process is running?

You need to use Microsoft's OOTB tasklist.exe utility that comes with Windows and available at C:\windows\system32\tasklist.exe. And the following line:

Process p = Runtime.getRuntime().exec("tasklist.exe");

will execute it. Then you can read this string with Scanner until it has next line. The following code gives you the list of running programs (foreground as well as background applications) running on your system:

public static void main(String[] args) throws IOException {
Process process = Runtime.getRuntime().exec("tasklist.exe");
Scanner scanner = new Scanner(new InputStreamReader(process.getInputStream()));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}

You'll get the output like this:
Sample Image

Get Command Line of a java process

You can get it with WMIC

C:\> wmic process where(name="javaw.exe") get commandline

How can I kill a process from a Java application, if I know the PID of this process? I am looking for a cross-platfrom solution

Since Java 9 there's ProcessHandle which allows interaction with all processes on a system (constrained by system permissions of course).

Specifically ProcessHandle.of(knownPid) will return the ProcessHandle for a given PID (technically an Optional which may be empty if no process was found) and destroy or destroyForcibly will attempt to kill the process.

I.e.

long pid = getThePidViaSomeWay();
Optional<ProcessHandle> maybePh = ProcessHandle.of(pid);
ProcessHandle ph = maybePh.orElseThrow(); // replace with your preferred way to handle no process being found.
ph.destroy(); //or
ph.destroyForcibly(); // if you want to be more "forcible" about it


Related Topics



Leave a reply



Submit