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

本文通过一个Java示例程序演示了如何使用Runtime类获取当前Java进程的内存使用情况,并通过主动调用GC来观察其对内存的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概要

主要用下列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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值