Java Memory

JVM calls system.gc() periodically to free memory, when the max heap size is reached, it will throw OutOfMemory exception at run time.

gc calls finalize() of the object to be released.

read article http://www.javaworld.com/javaworld/jw-06-1998/jw-06-techniques.html?page=1 to understand what is finalize() to be used. It is used when freeing non memory finite resources. also, when calling finalize() explictly, calling system.gc() is suggested.

for an example of java garbage collection see http://www.janeg.ca/scjp/gc/finalize.html

Stack vs. Heap

A java class is stored in JVM Heap. Java primitive variables are stored in stack if they are local method variables and stored in heap if they are class method variables. Multiple threads share the same heap but each thread has its own stack.

How to resolve out of memory issue

http://java.dzone.com/news/how-fix-memory-leaks-java