Java Memory Usage getMemoryUsage()

Here you can find the source of getMemoryUsage()

Description

Report memory usage, including used memory, free memory, total memory, and the maximum memory allotable to the JVM

License

Open Source License

Declaration

public static String getMemoryUsage() 

Method Source Code


//package com.java2s;

import java.text.DecimalFormat;

public class Main {
    /** Report memory usage, including used memory, free memory, total memory, and the maximum memory allotable to the JVM */
    public static String getMemoryUsage() {
        Runtime rt = Runtime.getRuntime();
        long max = rt.maxMemory();
        long total = rt.totalMemory();
        long free = rt.freeMemory();
        return String.format("Memory used: %s, free: %s, total: %s, max: %s", formatMemory(total - free),
                formatMemory(free), formatMemory(total), formatMemory(max));
    }//from www.  j a  v a2 s .c  o  m

    /** Format a memory value (in Bytes) using the appropriate units */
    public static String formatMemory(long mem) {
        String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
        double asDouble = (double) mem;
        int unit = 0;
        while (asDouble > 1000.0) {
            unit += 1;
            asDouble /= 1000.0;
        }
        return new DecimalFormat("#.0").format(asDouble) + " " + units[unit];
    }
}

Related

  1. getMemoryUsage()
  2. getMemoryUsage()
  3. getMemoryUsage()
  4. getMemoryUsage()
  5. getMemoryUsage()
  6. getMemoryUsage()
  7. getMemoryUsage()
  8. getMemoryUsage()
  9. getMemoryUsage()