get Memory Status - Java java.lang

Java examples for java.lang:Runtime

Description

get Memory Status

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getMemoryStatus());
    }//  w w  w. j  av a 2s. c o m

    public static String getMemoryStatus(boolean preRunGarbageCollector) {
        getRuntimeAndRunGC(preRunGarbageCollector);
        return "# Memory(MB): Total=" + getTotalMemory(false) + ", Used="
                + getConsumedMemory(false) + ", Free="
                + getFreeMemory(false);
    }

    public static String getMemoryStatus() {
        return "# Memory(MB): MaxMem=" + getMaxMemory() + ", Used="
                + getConsumedMemory(false);
    }

    private static Runtime getRuntimeAndRunGC(boolean preRunGarbageCollector) {
        Runtime rt = Runtime.getRuntime();
        if (preRunGarbageCollector) {
            rt.gc();
        }
        return rt;
    }

    public static long getTotalMemory(boolean preRunGarbageCollector) {
        Runtime rt = getRuntimeAndRunGC(preRunGarbageCollector);
        return bytesToMegabytes(rt.totalMemory());
    }

    public static long getTotalMemory() {
        return bytesToMegabytes(Runtime.getRuntime().totalMemory());
    }

    public static long getConsumedMemory(boolean preRunGarbageCollector) {
        Runtime rt = getRuntimeAndRunGC(preRunGarbageCollector);
        return bytesToMegabytes(rt.totalMemory() - rt.freeMemory());
    }

    public static long getFreeMemory(boolean preRunGarbageCollector) {
        Runtime rt = getRuntimeAndRunGC(preRunGarbageCollector);
        return bytesToMegabytes(rt.freeMemory());
    }

    public static long getMaxMemory() {
        return bytesToMegabytes(Runtime.getRuntime().maxMemory());
    }

    private static long bytesToMegabytes(long bytes) {
        long MEGABYTE = 1024L * 1024L;
        return bytes / MEGABYTE;
    }
}

Related Tutorials