Java Memory Management

Source: Internet
Author: User

1. Heap Memory and Non-heap Memory)

The Java virtual machine has a Heap. The Heap is the runtime data area. The Memory of all class instances and arrays is allocated from this place. The Heap Memory is created when the Java Virtual Machine is started, the memory available for Java code is reserved for developers. By default, when the free heap memory is less than 40%, the JVM will increase the heap until the maximum limit of-Xmx can be changed from-XX: minHeapFreeRatio is specified. By default, when the free heap memory is greater than 70%, the JVM will reduce the minimum heap limit until-Xms can be specified by-XX: MaxHeapFreeRatio.

Non-heap Memory is outside the JVM heap, and Non-heap Memory is reserved for the JVM, including the memory required for Method Area, JVM internal processing or optimization (such as JITCompiler, Just-in-time Compiler, and instantly compiled code cache), the code of each class structure (such as the runtime data pool, field, and method data) and method and constructor.

 

2. Java object status

GC records and manages all objects in heap by Directed Graphs. This method is used to determine which objects are "reachable", which objects are "recoverable", and which objects are "inaccessible ". When more than one reference exists for an object, the object is "reachable". When no reference exists for an object, the object is "recoverable". when the finalize () method is called by the object, there is still no reference, and the object is "inaccessibility". When the GC determines that some objects are "inaccessibility, GC recycles the memory space.

 

3. Java Memory Allocation

 

A) JVM will try to initialize a memory area for the relevant Java object in Eden.

B) When the Eden space is sufficient, the memory application ends; otherwise, the next step is reached.

C) JVM tries to release all inactive objects in Eden (which belongs to 1 or more advanced garbage collection). If the Eden space is not enough to put new objects, try to put some active objects in Eden into the same vor Area

D) The primary vor area is used as the intermediate swap area of Eden and OLD. When the OLD area has enough space, the objects in the primary vor area will be moved to the Old area. Otherwise, they will be kept in the primary vor area.

E) When there is not enough space in the OLD area, the JVM will perform full garbage collection in the OLD area (Level 0)

F) After full garbage collection, if the primary VOR and OLD areas still cannot store some objects copied from Eden, the JVM cannot create a memory area for the new object in the Eden area, the error "out of memory" appears.

 

4. Java generational GC

The Memory allocated by Java applications comes from Heap Memory ). For example, the heap memory is divided into three generations: Young, Old, and Perm.

A) In Young Generation, there is a Space called Eden Space, mainly used to store new objects, and there are two consumer vor Spaces (from, to) which are always the same size, they are used to store objects that survive each garbage collection. The Copying algorithm is generally used for garbage collection, which is fast. During each GC, the surviving objects are first copied from Eden to a certain sequence vorspace. When the sequence vor Space is full, the remaining live objects are directly copied to OldGeneration. Therefore, after each GC, the Eden memory block is cleared.

B) in Old Generation, it mainly stores memory objects with long lifecycles in applications. The mark-compact algorithm is generally used for garbage collection, which is slower, but reduces memory requirements.

C) garbage collection is divided into multiple levels. garbage collection in the OLD section will be collected if grade 0 is Full. garbage collection in grade 1 or above is partial, only spam in Young will be recycled; "out of memory" usually occurs after garbage collection in the OLD or Perm segments, there is still no memory space to accommodate new Java objects.

D) Cause of Full GC. There are many New objects, but they are not automatically released-> the Eden memory is not enough-> the object is constantly migrated to the Old-> the Old is Full-> Full GC

 

5. incremental GC

Incremental GC (Incremental GC) is implemented by one or more processes in JVM. It also occupies heap space like user programs, CPU usage during running. The application stops running when the GC process is running. Therefore, when GC runs for a long time, the user can feel the pause of the Java program. On the other hand, if GC runs for a short time, the object recovery rate may be too low, this means that many objects that should be recycled are not recycled and still occupy a large amount of memory. Therefore, we must weigh the pause time and recovery rate when designing GC. A good GC implementation allows users to define the settings they need. For example, some devices with limited memory are very sensitive to memory usage, and GC is expected to accurately recycle the memory, it does not care about the speed of the program. In addition, some real-time online games cannot allow long periods of program interruptions.

Incremental GC divides a long interrupt into many small interruptions through a certain collection algorithm, which reduces the impact of GC on user programs. Although the overall performance of incremental GC may be less efficient than that of normal GC, it can reduce the maximum pause time of the program.

The HotSpot JVM provided by Sun JDK supports incremental GC. By default, HotSpot JVM does not use incremental GC. To start incremental GC, we must add the-Xincgc parameter when running Java programs.

HotSpot JVM incremental GC is implemented using the Train GC algorithm. Its basic idea is to group (layer) all objects in the heap according to creation and usage ), put frequently-used and highly-correlated objects in a team and adjust the group as the program runs. When GC is run, it always recycles the oldest (rarely accessed recently) Objects first. If the entire group is recyclable, GC recycles the entire group. In this way, each GC operation only recycles a certain percentage of inaccessible objects to ensure smooth operation of the program.

 

6. finalize method of Objects

The finalize method is defined in the Object. If the finalize method is implemented before the memory occupied by an object is recycled, the method will be called. At the same time, the uncaptured exception thrown by this method will only cause the finalize execution of the object to exit. Suggestions for using the finalize method:

A) Most importantly, do not use finalize as much as possible. It is too complicated, or it is better for the system to take care of it. You can define other methods to release non-memory resources.
B) If used, it should be as simple as possible.
C) if it is used to avoid object regeneration, you may find trouble for yourself.
D) It can be used to protect non-memory resources from being released. Even if we define other methods to release non-memory resources, others may not call this method to release the resources. In finalize, you can check whether the instance is released. If the instance is not released, it is better to release the instance later than not.
E) even if the finalize of an object is already running, the object cannot be destroyed. To implement some actions to ensure that the object is completely destroyed, you can only rely on classes in java. lang. ref to interact with GC.

F) After finalize is run, the object may become reachable. GC also checks whether the object is reachable again. Therefore, using finalize will reduce the Running Performance of GC.

G) since the time for GC to call finalize is uncertain, releasing resources in this way is also uncertain.

 

7. GC program interaction

The Java 2 platform introduces the java. lang. ref package, including classes that allow you to reference objects without leaving them in memory. These classes also provide limited interaction with the garbage collector.

A) StrongReference is a kind of reference that you usually establish. This reference is highly accessible and will not be automatically recycled by the garbage collector.

B) SoftReference is similar to dispensable items. If the memory space is sufficient, the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache.

D) WeakReference is similar to something dispensable. When the Garbage Collector thread scans the memory area under its jurisdiction, its memory will be recycled no matter whether the current memory space is sufficient or not.

E) The PhantomReference parameter is "Virtual Reference", which is different from other references. Virtual Reference does not determine the object lifecycle. If an object only holds a virtual reference, it may be reclaimed at any time, that is, its get method returns null at any time. Virtual references are mainly used to track the activity of objects being reclaimed by garbage collection. It must be used together with the ReferenceQueue, which is the biggest difference from weak references and soft references.

 

8. Optimization suggestions

A) if the object is listened on, you must first remove the listener before setting it to null.

B) Set unnecessary objects to null as soon as possible.

C) cache frequently used objects

D) Use reference for Interaction

E) Release reference of useless objects as soon as possible. A good way is to enable the reference variable to be automatically set to null after exiting the active domain when using a temporary variable, suggesting that the Garbage Collector collects the object to prevent memory leakage. For instances with pointers, jvm will not recycle this resource, because garbage collection will take null objects as garbage, improving the efficiency of GC collection mechanism;

E) In our program, it is inevitable that a large amount of String processing is used to avoid the use of String. StringBuffer should be used in large quantities. Each String object must occupy an independent area of memory;

G) Use as few static variables as possible, because static variables are global and GC will not be recycled;

H) Avoid creating objects in a centralized manner, especially large objects. JVM will suddenly need a large amount of memory, which will inevitably trigger GC to optimize the system memory environment. The declared array space is displayed, and the number of applications is large.

(I) try to use the object pool technology to improve system performance. Objects with long lifecycles that have short lifecycles are prone to memory leakage, for example, when a large collection object has a large data volume of business objects, you can consider processing them in multiple parts,

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.