`
yutiansky
  • 浏览: 194097 次
  • 性别: Icon_minigender_1
  • 来自: 本溪
社区版块
存档分类
最新评论

(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;
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics