I am currently hosting a java server program(craftbukkit), and it seems that when I try to get the RAM usage from the server program(craftbukkit), it doesn't return the actual used RAM, but rather somewhere around half of what it's using. (though it's not always exactly half, so it's impossible to estimate actual RAM usage this way).
I was wondering how I might go about getting the actual RAM used by the java process, as seen in the system monitor tool(on linux), this way I would be able to retrieve the amount of RAM used as reported to the system.
I saw an example previously using the PID of the process, but I don't know how to go about getting the PID of the process, knowing only the name.(only one java instance is running, so we don't have to worry about getting the wrong result)
Thanks ahead of time!
With ps -ef | grep "java" I get the following output
prodynamics@prodynamics:~$ ps -ef | grep "java"
1000 22292 29385 75 12:08 pts/0 00:42:19 java -Xmx3100M -Xms1024M -XX:MaxPermSize=248m -jar craftbukkit.jar
1000 23544 23443 0 13:04 pts/2 00:00:00 grep java
But with ps -eo pid | grep "java" The console returns no results at all. Though to my understanding it should return the PID.
I was able to succesfully get the PID with the following
ps -eo pid,comm | grep 'java$' | awk '{print $1}' | head -1
You can try the following, if you really need to get it:
ps -ef | grep "java" | grep -v -i "grep" | cut -d ' ' -f 7
This will only return the PID of the java process, and will exclude the grep
call that you make this way. It might need some tweaking of the 7 on the end, depending on your system.
What it does, is take all the results from ps -ef
and filter to only those containing java
, but not containing grep
. Then it cuts the result at every space, and returns field 7 (where the 7 is the number on the end)
You don't need to lose your time with ps
, pipes, grep
a.o. All you need is pgrep
:
pgrep java
See man pgrep
for more info.
You can also retrieve the PID from your Java application, using the platform runtime MXBean's getName()
method:
import java.lang.management.ManagementFactory;
public class Pid {
/**
* Return the current process ID.
* @return the pid as an int, or -1 if the pid could not be obtained.
*/
public static int getPID() {
int pid = -1;
// we expect the name to be in '<pid>@hostname' format - this is JVM dependent
String name = ManagementFactory.getRuntimeMXBean().getName();
int idx = name.indexOf('@');
if (idx >= 0) {
String sub = name.substring(0, idx);
try {
pid = Integer.valueOf(sub);
System.out.println("process name=" + name + ", pid=" + pid);
} catch (Exception e) {
System.out.println("could not parse '" + sub +"' into a valid integer pid :");
e.printStackTrace();
}
}
return pid;
}
}