开发者

How can I retrieve the amount of free RAM from a Java program?

Free 开发者_高级运维RAM: my target metric.

Java: my tool of choice.

???: a good way to get the former using the latter.


Probably like this, using Java Native Interface (JNI) :

    Kernel32 lib = (Kernel32) Native.loadLibrary ("kernel32",Kernel32.class);           
    Kernel32.MEMORYSTATUS mem = new Kernel32.MEMORYSTATUS ();
    lib.GetMem(mem);
    System.out.println ("Available physical memory " + mem.dwAvailPhys);


Difficult to do without resorting to non-portable or native libraries.

Something like

Runtime.getRuntime().freeMemory()

will only return the memory available to the JVM, which may not be the same as the system-wide available memory.

This page provides a good rundown.

http://blog.codebeach.com/2008/02/determine-available-memory-in-java.html


To get the Free RAM by executing the command free -m and then interpreting it as below:

Runtime runtime = Runtime.getRuntime();

BufferedReader br = new BufferedReader(
    new InputStreamReader(runtime.exec("free -m").getInputStream()));

String line;
String memLine = "";
int index = 0;
while ((line = br.readLine()) != null) {
  if (index == 1) {
    memLine = line;
  }
  index++;
}
//                  total        used        free      shared  buff/cache   available
//    Mem:          15933        3153        9683         310        3097       12148
//    Swap:          3814           0        3814

List<String> memInfoList = Arrays.asList(memLine.split("\\s+"));
int totalSystemMemory = Integer.parseInt(memInfoList.get(1));
int totalSystemUsedMemory = Integer.parseInt(memInfoList.get(2));
int totalSystemFreeMemory = Integer.parseInt(memInfoList.get(3));

System.out.println("Total system memory in mb: " + totalSystemMemory);
System.out.println("Total system used memory in mb: " + totalSystemUsedMemory);
System.out.println("Total system free memory in mb: "   + totalSystemFreeMemory);


I know of two projects that have purchased JNIWrapper and have been happy with the result. Both Windows - based usage. When I embedded it on our current project, we wanted to know how much free ram was available when users launched our app (WebStart) since there were lots of performance complaints which were hard to investigate (we suspected RAM issues). JNIWrapper helps us to collect stats at startup about free ram, total and CPU etc so if a user group is complaining, we can check our stats to see if they have been given dodgy machines. Life saving.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜