Memory optimization for Java programs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.