Memory stats

The memory available to your Java program has an upper limit. To specify that limit explicitly, instead of relying on a default value, you can pass a command line parameter named -Xmx to the Java runtime.

It's usually important to know how much memory your app is using. If you're using a high percentage of the total available memory, then it's usually a good idea to use -Xmx to increase the total available.

Here's an example. (An explanation of methods of the Runtime class can be found here.)

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Objects;

/** All values are in bytes. */
public class PercentMemory {
  
  public static void main(String... args) {
    log("Memory stats:");
    PercentMemory pm = new PercentMemory();
    log(" Total:  " + pm.format(pm.totalAvailableMemory()) + " bytes (-Xmx setting)");
    log(" In-use: " + pm.format(pm.currentlyUsedMemory()) + " bytes");
    log(" In-use: " + pm.percentageMemoryUse(NUM_DECIMALS) + " %");
  }
  
  /** 
   This is the -Xmx setting passed to the java command line.
   Example: -Xmx=10G. 
  */
  Long totalAvailableMemory(){
    return jre().maxMemory();
  }
  
  Long currentlyUsedMemory(){
    return jre().totalMemory() - jre().freeMemory();
  }
  
  Long currentlyFreeMemory(){
    return totalAvailableMemory() - currentlyUsedMemory();
  }
  
  BigDecimal percentageMemoryUse(int numDecimals){
    BigDecimal currentlyUsed = new BigDecimal(currentlyUsedMemory().toString()); 
    BigDecimal totalAvailable = new BigDecimal(totalAvailableMemory().toString());
    BigDecimal HUNDRED = new BigDecimal("100");
    BigDecimal result = currentlyUsed.divide(
      totalAvailable, numDecimals, RoundingMode.HALF_EVEN
    );
    result = result.multiply(HUNDRED);
    return result.stripTrailingZeros();
  }
  
  private Runtime jre(){
    return Runtime.getRuntime();
  }
  
  private String format(Number value){
    DecimalFormat formatter = new DecimalFormat("#,###");
    return formatter.format(value);
  }
  
  private static void log(Object thing){
    System.out.println(Objects.toString(thing, ""));
  }

  private static int NUM_DECIMALS = 6; //before the *100 operation
}
 

Example run:

Memory stats:
 Total:  2,734,686,208 bytes (-Xmx setting)
 In-use: 1,929,416 bytes
 In-use: 0.0706 %