Recently, I was asked by a newbie about Memory Leaks in Java. He had just stepped into the world of Java & wasn't sure about Garbage Collection & Memory Leaks in Java. He asked me if it was possible to show an instance of Memory Leak in Java.
The question has been adressed numerous time ever since the first Java Version rolled out. A lot of examples are availale on the net that show how to get a Memory Leak from Java.
I wrote this example on the fly & wanted to save it for posterity :-
import java.util.ArrayList;
public class MemoryLeakSimulator
{public static void main(String[] args)
{
try{
System.out.println(" MemoryLeakSimulator.main() :: Start :: Leak ");
ArrayList objHeapPigArrayList = new ArrayList();
ArrayList objHeapSinkArrayList = new ArrayList();
for(long lCounter = 0;
lCounter <>
lCounter ++
)
{
objHeapSinkArrayList = new ArrayList();
objHeapPigArrayList.add(objHeapSinkArrayList);
}
System.out.println(" MemoryLeakSimulator.main() :: End :: Leak ");
}
catch (Throwable objThrowable)
{
objThrowable.printStackTrace(System.out);
}// end of the try block}// end of main() method
}// end of MemoryLeakSimulator
There is nothing new or innovative in the code - Objects are created in the "Heap" memory of the JVM. The Garbage Collection tries to free the menmory used by "unreferencable" object. However, in this case, we are continously pumping objects to the ArrayList & at a critical time, you may notice this error :-
..................
...................
...................
[Full GC 60651K->60648K(65088K), 0.3803447 secs]
[Full GC 65087K->65086K(65088K), 0.4023478 secs]
[Full GC 65086K->65086K(65088K), 0.3938506 secs]
java.lang.OutOfMemoryError: Java heap space
That's the meat of it !
Also, every Memory Leak ( at least in 1.5 ) generates a hs_err_pid*.log file. It gives a lot of useful information.