監控JVM記憶體使用情況,剩餘空間小於2M時報警

FrankYou發表於2018-08-27

一個簡單的類,用來監控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);
        }
    }

}

 

相關文章