Wednesday 19 August 2015

Java program to find out available free memory and memory used by the application


               Java program to find out available free memory and memory used by the application



Suppose you want to know the memory used by your application and available system memory in order to check the performance of your application.

Here is the implementation to know free memory and memory used by your application:-


/**  
  * @author Dixit  
  *   
  */  
 public class MemoryUtils {  
      public static void main(String a[]) {  
           System.out.println("Percentage of Memory Used:"  
                     + getPercentageMemoryUsed());  
           System.out.println("Free memory in KBs:" + getFreeMemoryInKBs());  
      }  
      public static float getPercentageMemoryUsed() {  
           Runtime runtime = Runtime.getRuntime();  
           long memoryUsedByApplication = runtime.totalMemory()  
                     - runtime.freeMemory();  
           long maximumMemory = runtime.maxMemory();  
           float percentageMemoryUsed = ((memoryUsedByApplication / (float) maximumMemory) * 100);  
           return percentageMemoryUsed;  
      }  
      public static int getFreeMemoryInKBs() {  
           Runtime runtime = Runtime.getRuntime();  
           long memoryUsedByApplication = runtime.totalMemory()  
                     - runtime.freeMemory();  
           long maximumMemory = runtime.maxMemory();  
           long freeMemory = maximumMemory - memoryUsedByApplication;  
           int freeMemoryInKBs = (int) freeMemory / 1024;  
           return freeMemoryInKBs;  
      }  
 }  



Enjoy programming :)

No comments:

Post a Comment