Java Notes

OutOfMemoryError

If your Java program is running out of memory, there are several things you can do.
  1. Make unused objects garbage collectable.
  2. Avoid excessive object creation.
  3. Allocate more memory for the heap.
  4. 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.

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]