Thursday, February 24, 2011

How To Manage Memory With Java

Java provides automatic garbage collection,sometimes you will want to know how large the object heap is and how much of it is left. You can use this result to know about the efficiency of your application or program, that is you may come to know how many more objects you can instantiate. To obtain these values use totalMemory() and freeMemory() methods.

Since Java Garbage Collector runs periodically to check the dangling object references and empty Strings and to recycle these unused objects. However on the other hand we can let the garbage collector run whenever we want. Garbage collector runs on random times, you never know when will be the next appointment of Garbage Collector. So, f you think you are running out of memory you can enforce Garbage Collector to Sweep unused memory. You can run the Garbage Collector on demand by calling gc() method. gc() is called as "System. gc()". A good practice is to first call gc() method then call freeMemory() to get the base memory usage. Next execute your code and now see how much memory code is occupying by again calling freeMemory() method.

NOTE:-The methods gc(), totalMemory(), freeMemory() are part of Runtime class(For more on Runtime refer its Runtime API). The gc() method is also available in System class and is marked static in it.

Lets understand by example:-

public class Memoryusage{
public static void main(String a[]){
Runtime rt = Runtime. getRuntime();
long mem1,mem2;
String toomuch[] = new String[20000];
System. out. println("Total memory is : "+rt. totalMemory());
mem1=rt. freeMemory();
System. out. println("Initial Free Memory : "+mem1);
rt. gc();
mem1=rt. freeMemory();
System. out. println("Memory after Garbage Collection :"+mem1);
for(int i=0;i<20000;i++)
toomuch[i] = new String("String Array");


mem2=rt. freeMemory();
System. out. println("Memory after allocation :"+mem2);
System. out. println("Memory used by alocation : "+(mem1-mem2));

for(int i=0;i<1000;i++)
toomuch[i] = null;
rt. gc();
mem2=rt. freeMemory();
System. out. println("Memory after deacllocating memory : "+mem2);
}
}

Output:-

Total memory is : 5177344
Initial Free Memory : 4898608
Memory after Garbage Collection :4986512
Memory after allocation :4505976
Memory used by allocation : 480536
Memory after deacllocation memory : 4530512

Output is Machine specific and may vary on your machine.

Now you can see that how these methods work gc(),freeMemory() and totalMemory(). Runtime class is an abstract class thus it cannot be used to create instances but despite we can all methods to do the same. Like here we have called method getRuntime().

No comments:

Post a Comment