by, 05-25-2011 at 10:04 AM (2811 Views)
You are aware of the fact that garbage collection collects and removes all the unwanted objects from memory without used intervention. But sometimes, you run into memory leaks problems that demands investigation. I will shed some light on this issue in the next few posts.
The Java GC process is a low-priority thread and it constantly searches memory for unreachable objects that are not reachable by any live thread. Different JVMs use different algorithms to determine how to collect garbage most efficiently.
Let me now tell you about how JVM uses heap and stack.
JVM uses stack to store local variables which are declared in methods and constructors. Local variables are allocated when a method is invoked and de-allocated when the method is exited.
Heap is a place where all objects created with the new keyword are allocated.
Local variables are few in number with only primitive types and references, so usually the stack will not overflow. Some times in special cases like unusually deep or infinite recursion may cause stack overflow. The JVM throws a Java out-of-memory error if it is not able to get more memory in the heap to allocate more Java objects. If heap is full, then the JVM cannot allocate more objects as it is unable to expand further.
The four typical causes of memory leaks in a Java program are:
- Unknown or unwanted object references
- Long-living (static) objects
- Failure to clean up or free native system resources
- Bugs in the JDK or third-party libraries