I would like to consult memory used at the instant by MySQL, MongoDB and Neo4j using java. I've searched for it, but didn't found anything relevant. My OS is Windows and i am using Eclipse. Thanks
Acess memory in task manager using java
187 Views Asked by Rodrigo At
2
There are 2 best solutions below
0

There is nothing that I know of in the API of the JDK that can query processes of the host operating system. Hence the only option that I can think of is to use class ProcessBuilder
to execute a host OS command.
Since you state that your OS is Windows, the following PowerShell command will output the process name and memory usage of your selected processes.
Get-Process | Where-Object {$_.ProcessName -in 'MySQL','MongoDB','Neo4j'} | Select-Object -Property 'ProcessName','WorkingSet' | Format-Table -HideTableHeaders
Note that I am not sure about the process names because I don't use any of MySQL, MongoDB or Neo4j. I assume that you do know the correct process names so remember to correct them in the above command before you run it.
The below code uses ProcessBuilder
to run the above [PowerShell] command and redirects the command output to System.out
import java.io.IOException;
import java.lang.ProcessBuilder;
public class PrcBldT2 {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"Get-Process | Where-Object {$_.ProcessName -in 'eclipse','oracle'} | Select-Object -Property 'ProcessName','WorkingSet' | Format-Table -HideTableHeaders");
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
try {
Process p = pb.start();
int result = p.waitFor();
System.out.println("Exit status = " + result);
}
catch (IOException | InterruptedException x) {
x.printStackTrace();
}
}
}
I just came up with a java code template to run a windows command, you need to run
tasklist
command to have all the process table with all information including memory used by each process.Here is the code:
I just edit my solution so that it can grab just mysql, mongodb and neo4j process.