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.
* 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.
1 comment:
very good this is very helpful.
OutofMemory" error message appears when you have a large number of programs running.
This can have two reasons:
* Your Java application has a memory leak. There are tools like YourKit Java Profiler that help you to identify such leaks.
* Your Java application really needs a lot of memory (more than 128 MB by default!). In this case the Java heap size can be increased using the following runtime parameters:
java -Xms initial heap size -Xmx maximum heap size
Defaults are:
java -Xms32m -Xmx128m
Post a Comment