ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

What is Runtime class ?

Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.

 

Getting free memory, total memory and max memory on JVM is using by Runtime class in Java. and many java programmer is interested to know whether they have any relationship with JVM argument -Xms and -Xmx which is used to specify starting heap size and maximum heap size of JVM.

 

In order to get currently free Memory available for creating object use Runtime.getRuntime().freeMemory() method, this will return size in bytes,

 

You can use Runtime.getRuntime.totalMemory() to get total memory from JVM which represent current heap size of JVM which is combination of used memory currently occupied by objects and free memory available for new objects.

 

public class MemoryUtil{

 

       private static final int MegaBytes = 10241024;

 

       public static void main(String args[]) {

 

              long freeMemory = Runtime.getRuntime().freeMemory()/MegaBytes;

              long totalMemory = Runtime.getRuntime().totalMemory()/MegaBytes;

              long maxMemory = Runtime.getRuntime().maxMemory()/MegaBytes;

 

              System.out.println("JVM freeMemory: " + freeMemory);

              System.out.println("JVM totalMemory also equals to initial heap size of JVM : "

                                         + totalMemory);

              System.out.println("JVM maxMemory also equals to maximum heap size of JVM: "

                                         + maxMemory);

 

              ArrayListnew ArrayList

 

              for (int i = 0; i < 10000000; i++) {

                     objects.add(("" + 10 * 2710));

              }

 

              freeMemory = Runtime.get  MockB b = new MockB();

Runtime().freeMemory() / MegaBytes;

              totalMemory = Runtime.getRuntime().totalMemory() / MegaBytes;

              maxMemory = Runtime.getRuntime().maxMemory() / MegaBytes;

 

              System.out.println("Used Memory in JVM: " + (maxMemory - freeMemory));

              System.out.println("freeMemory in JVM: " + freeMemory);

              System.out.println("totalMemory in JVM shows current size of java heap : "

                                         + totalMemory);

              System.out.println("maxMemory in JVM: " + maxMemory);

 

       }

}

Related Posts Plugin for WordPress, Blogger...
Flag Counter