Java Memory Information getMemoryStatus(boolean preRunGarbageCollector)

Here you can find the source of getMemoryStatus(boolean preRunGarbageCollector)

Description

get Memory Status

License

Open Source License

Declaration

public static String getMemoryStatus(boolean preRunGarbageCollector) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String getMemoryStatus(boolean preRunGarbageCollector) {
        getRuntimeAndRunGC(preRunGarbageCollector);
        return "# Memory(MB): Total=" + getTotalMemory(false) + ", Used=" + getConsumedMemory(false) + ", Free="
                + getFreeMemory(false);/*from www  .ja  v a  2 s . c  o m*/
    }

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

    private static Runtime getRuntimeAndRunGC(boolean preRunGarbageCollector) {
        Runtime rt = Runtime.getRuntime();
        if (preRunGarbageCollector) {
            //long startTime = System.currentTimeMillis();                               //DEBUG
            rt.gc();
            //System.out.println("GC takes "+(System.currentTimeMillis()-startTime)+" ms.");   //DEBUG
        }
        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

  1. getMemoryInfo()
  2. getMemoryLimit()
  3. getMemoryLimitMinSize()
  4. getMemoryStats()
  5. getMemoryStats(int mode)
  6. getMemoryString()
  7. getMemoryString()
  8. getMemoryUtilizationPercent()
  9. getNowMemoryStatus()