监控JVM内存使用情况,剩余空间小于2M时报警

时间:2022-05-31 20:26:44

一个简单的类,用来监控JVM内存使用情况,剩余空间小于2M时报警。

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method; /**
* Test
*/
public class Test { public static void main(String[] args) throws InterruptedException {
Runtime runtime = Runtime.getRuntime();
while (true) {
long freeMemory = runtime.freeMemory();
long totalMemory = runtime.totalMemory();
long maxMemory = runtime.maxMemory();
String msg = "max:" + (maxMemory / 1024 / 1024) + "M,total:" + (totalMemory / 1024 / 1024) + "M,used:"
+ ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M,free:"
+ (freeMemory / 1024 / 1024) + "M"; boolean ok = (maxMemory - (totalMemory - freeMemory) > 2048); // 剩余空间小于2M报警
if (!ok) {
System.out.println(msg);
System.err.println("剩余空间小于2M报警");
}
Thread.currentThread().sleep(1 * 1000);
}
} }