Interviews are often asked about Java's garbage collection mechanism, which is rarely used to write code, but it is important to focus on the program's memory optimization. "Effectivejava" This book has a few speak very good, take come to summarize next.
First, a simple summary of the Java Memory Recovery mechanism.
Java memory is primarily heap memory and stack memory, and the memory in the stack is recycled after the program runs outside the scope. The memory in the heap will be reclaimed by a specific algorithm at a certain time period when no reference is directed to the JVM virtual machine.
Usually write program note the following points, the program for memory optimization
1. Avoid creating unnecessary objects
A. Use base type to override boxing type (enjoy meta mode)
B, StringBuffer instead of string
C. Using singleton mode (not recommended for lazy loading)
D, if a frequently called method, each call requires a power object, consider static initialization. such as the Clendar instantiation
Note: The creation and recycling of small objects is very inexpensive, and by creating additional objects the clarity, simplicity, and functionality of the promotion program is highly recommended. It is not recommended to use a pool of objects that you maintain.
2. Eliminate references to outdated objects
A, for a similar array, the object container in the collection, after use, can be empty.
b, use Weakhashmap to do the cache.
3. Minimizing the scope of local variables
A, declare the variable the first time you use a local variable
Memory optimization for Java programs