tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Runtime > JVM Memory

JVM Memory 

The following code shows how to access available, total and maximum memory of JVM using Runtime.

File Name  :  
com/bethecoder/tutorials/runtime/RuntimeInfoTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.runtime;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class RuntimeInfoTest {

  public static void main(String[] args) {
    
    System.out.println("Number of processors available to the JVM : " 
        Runtime.getRuntime().availableProcessors());
    
    System.out.println("Free memory in the JVM : " 
        bytes2String(Runtime.getRuntime().freeMemory()));
    
    System.out.println("Total memory in the JVM : " 
        bytes2String(Runtime.getRuntime().totalMemory()));
    
    System.out.println("Maximum amount of memory that the JVM will attempt to use : " 
        bytes2String(Runtime.getRuntime().maxMemory()));
    
  }
  
  public static final long SPACE_KB = 1024;
  public static final long SPACE_MB = 1024 * SPACE_KB;
  public static final long SPACE_GB = 1024 * SPACE_MB;

  public static String bytes2String(double dataSize) {
    
    NumberFormat nf = new DecimalFormat();
    nf.setMaximumFractionDigits(2);
    
    try {
      if dataSize < SPACE_KB ) {
        return nf.format(dataSize" Bytes";
      else if dataSize < SPACE_MB ) {
        return nf.format(dataSize/SPACE_KB" KB";
      else if dataSize < SPACE_GB ) {
        return nf.format(dataSize/SPACE_MB" MB";
      else {
        return nf.format(dataSize/SPACE_GB" GB";
      }          
    catch (Exception e) {
      return dataSize + " Bytes";
    }

  }/* end of bytes2String method */

}
   

It gives the following output,
Number of processors available to the JVM : 1
Free memory in the JVM : 4.74 MB
Total memory in the JVM : 4.94 MB
Maximum amount of memory that the JVM will attempt to use : 63.56 MB



 
  


  
bl  br