Java: OutOfMemoryError
If your Java program is running out of memory, there are
several things you can do.
- Make unused objects garbage collectable.
- Avoid excessive object creation.
- Allocate more memory for the heap.
- Choose an alternative technique (eg, caching).
First you should understand
where things are in memory, and typical reasons for
running out of memory.
Stack and Heap
Memory is allocated in two regions.
- The stack is where
local variables (declared in methods and constructors)
are allocated. Local varables are allocated when a method is
entered, and deallocated when the method is exited.
Because local variables are small, only primitive types
and references, it is very unlikely that the stack will
overflow, except in a case of unusually deep or infinite recursion.
- The heap is where all objects are allocated with
new
. It is the heap that is more likely
to run out of memory.
There are several approaches to solving out-of-memory
problems in the heap.
Make unused objects garbage collectable
Java's automatic garbage collection recycles an object's memory when
there is no active reference to it.
When you are finished using a large data structure, make sure there
are no references to it. It's easy to leave a reference to
unused object around. Assigning null
to the reference at the root of the data structure may be sufficient.
I wrote a program which processed source programs in three
phases, building a large data structure for the output of each
phase. I carelessly kept references to the data structures
from the first two phases, even tho I no longer needed them.
I was surprised to run out of memory. Simply assigning null
to these variables for the unused data structures solved my problem.
[MORE TO BE ADDED]