get Free Memory - Java java.lang

Java examples for java.lang:Runtime

Description

get Free Memory

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        boolean preRunGarbageCollector = true;
        System.out.println(getFreeMemory(preRunGarbageCollector));
    }//from  ww  w .j  a  va2s  . com

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

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

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

Related Tutorials