(java入门)内存消耗的调查

概要

主要用下列3个函数。

Runtime.getRuntime().freeMemory()

Runtime.getRuntime().totalMemory()

Runtime.getRuntime().maxMemory()

 

GC主动运行

System.gc()

 

package net.tianyu.sample;

import java.text.DecimalFormat;

public class TestGC {

	public static void main(String[] args) {

		byte[] buf = null;

		for (int i = 0; i < 10; i++) {
			buf = new byte[1000000];
			System.out.println(getMemoryInfo());
			System.gc();
		}
	}

	public static String getMemoryInfo() {
		DecimalFormat f1 = new DecimalFormat("#,###KB");
		DecimalFormat f2 = new DecimalFormat("##.#");
		long free = Runtime.getRuntime().freeMemory() / 1024;
		long total = Runtime.getRuntime().totalMemory() / 1024;
		long max = Runtime.getRuntime().maxMemory() / 1024;
		long used = total - free;
		double ratio = (used * 100 / (double) total);

		String info = "";
		info += "Java Memory : Total=" + f1.format(total) + ",\t";
		info += "Used=" + f1.format(used) + " (" + f2.format(ratio) + "%),\t";
		info += "MaxCanUse=" + f1.format(max);
		return info;
	}
}

你可能感兴趣的:(java,.net)