get Total Memory - Java java.lang

Java examples for java.lang:Runtime

Description

get Total Memory

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getTotalMemory());
    }/*from w w w.  java2  s.  c o m*/

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

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

    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