如何通过 Java 的运行时 api 获取 Java 程序使用的内存?
有类似的问题,但他们似乎避免回答这个具体问题。如何通过 Java 的运行时 api 获取 Java 程序使用的内存?
这里的答案表明我可以做这样的事情:
System.out.println("KB: " + (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024);
但是,无论我运行哪个程序,这总是返回相同的数字。例如,下面我有一个程序,无论我在地图中放入多少数字,内存使用量都保持不变。
package memoryTest;
import java.util.HashMap;
import java.util.Map;
public class MemoryTest {
static Map<Integer, NewObject> map = new HashMap<Integer, NewObject>();
public static void main(String[] args){
System.out.println("KB: " + (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024);
fillMemory(25);
System.out.println("KB: " + (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024);
}
static int j=0;
public static void fillMemory(int i){
for(int k=0; k< 2000; k++)
map.put(j++, new NewObject());
}
public static class NewObject{
long i = 0L;
long j = 0L;
long k = 0L;
}
}
通过 cambecc 的主要方法,输出是:
# 3085, Total: 128516096, Free: 127173744, Diff: 671120
# 173579, Total: 128516096, Free: 110033976, Diff: 671128
# 335207, Total: 128516096, Free: 92417792, Diff: 637544
# 672788, Total: 224198656, Free: 159302960, Diff: 1221520
# 1171480, Total: 224198656, Free: 106939136, Diff: 1221544
# 1489771, Total: 368377856, Free: 227374816, Diff: 1212984
# 1998743, Total: 368377856, Free: 182494408, Diff: 1212984