totalMemory()
freeMemory()
maxMemory()
先看第一段代码:
public class Memory_test
{
public static void main( String [] args ) throws Exception
{
Runtime r = Runtime.getRuntime();
long t1 = r.totalMemory()/1024;
long f1 = r.freeMemory()/1024;
System.out.println(t1+"KB"); // 本机输出结果: 5056KB
System.out.println(f1+"KB"); // 4821KB
}
}
5056 - 4821 = 235KB, 也就是虚拟机本身占用的内存。
再看下一段代码:
public static void main( String [] args ) throws Exception
{
Runtime r = Runtime.getRuntime();
String a[];
long t1 = r.totalMemory()/1024;
long f1 = r.freeMemory()/1024;
System.out.println(t1+"KB"); // 本机输出结果: 5056KB
System.out.println(f1+"KB"); // 4821KB
a = new String[110000];
for(int i= 0;i<110000;i++)
a[i] = "1";
long t2 = r.totalMemory()/1024;
long f2 = r.freeMemory()/1024;
System.out.println(t2+"KB"); // 5056KB
System.out.println(f2+"KB"); // 4391KB
}
f1 - f2 = 430KB, 也就是a[]占用的内存。
再看第三段代码:
public static void main( String [] args ) throws Exception
{
Runtime r = Runtime.getRuntime();
String a[];
long t1 = r.totalMemory()/1024;
long f1 = r.freeMemory()/1024;
System.out.println(t1+"KB"); // 本机输出结果: 5056KB
System.out.println(f1+"KB"); // 4821KB
a = new String[1100000]; //多一位
for(int i= 0;i<1100000;i++)
a[i] = "1";
long t2 = r.totalMemory()/1024;
long f2 = r.freeMemory()/1024;
System.out.println(t2+"KB"); // 9356KB
System.out.println(f2+"KB"); // 4917KB
}
可以看到,当初始的5056KB不够用来提供a[]的内存时候,java虚拟机有增加分配到了9356KB的内存空间,用来保证程序可用内存的空间,此时a[]占用的内存应该是 (t2-f2)-(t1-f1) = 4204KB
分析到此,应该可以知道用java调用一个程序需要的内存,可以前后取totalMemory(), freeMemory()来确定。
转载于:https://blog.51cto.com/alinazh/1279016