get Consumed Memory - Java java.lang

Java examples for java.lang:Runtime

Description

get Consumed Memory

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        boolean preRunGarbageCollector = true;
        System.out.println(getConsumedMemory(preRunGarbageCollector));
    }//from  w ww  . j a v a 2s .c o m

    public static long getConsumedMemory(boolean preRunGarbageCollector) {
        Runtime rt = getRuntimeAndRunGC(preRunGarbageCollector);
        return bytesToMegabytes(rt.totalMemory() - 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