Runtime类
一、单例类
Runtime.getRuntime();
二、常用方法
addShutdownHook(Thread);
removeShutdownHook(Thread);
exec(...);
availableProcessors();
freeMemory();
totalMemory(); // Xms ~ Xmx
maxMemory(); // Xmx
gc();
四、内存使用测试
Runtime rt = Runtime.getRuntime();
rt.gc();
System.out.println("totalMemory: " + rt.totalMemory());
System.out.println("maxMemory: " + rt.maxMemory());
List<String> list = new ArrayList<String>(1000000);
String str = "";
for (int i = 0; i < 10000; ++i) {
str += i % 10;
}
rt.gc();
System.out.println(rt.freeMemory() + "-" + (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()));
for (int i = 0; i < 1000000; ++i) {
list.add(new String(str));
if (i % 10000 == 0) {
rt.gc();
System.out.println(rt.freeMemory() + "-" + (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()));
}
}
VM arguments: -Xms10m -Xmx20m
一开始freeMemory的大小约为10m,随着可用内存的减少,中间有一次内存的增加,totalMemory最大可达到Xmx的设置值。