Java memory recovery mechanism and Java memory recovery mechanism

Source: Internet
Author: User

Java memory recovery mechanism and Java memory recovery mechanism

In Java, its memory management includes two aspects: Memory Allocation (when a Java object is created) and memory recovery. These two aspects are automatically completed by JVM, this reduces the learning difficulty of Java programmers and avoids the danger of Direct Memory operations like C/C ++. However, because the JVM is responsible for memory management, many Java programmers no longer care about memory allocation, resulting in inefficient and memory consumption for many programs. Therefore, Java programmers should understand JVM at the end to write programs that are more efficient and fully utilize limited memory.

1. Java status in memory

First, we will write an example code:

Person. java

12345678910111213141516171819 packagetest;  importjava.io.Serializable;  publicclassPersonimplementsSerializable {      staticfinallongserialVersionUID = 1L;      String name; // Name      Person friend;    // Friend      publicPerson() {}      publicPerson(String name) {         super();         this.name = name;     } }

Test. java

1234567891011121314 packagetest;  publicclassTest{      publicstaticvoidmain(String[] args) {         Person p1 = newPerson("Kevin");         Person p2 = newPerson("Rain");         Person p3 = newPerson("Sunny");          p1.friend = p2;         p3 = p2;         p2 = null;     } }

Run Test. in java, the object reference in the main aspect draws an object reference graph starting from the main method (the vertex is the object and reference, and the directed edge is the reference relationship ):

After running the program, you can view its status in the memory as a directed graph, which can be divided into three types:

1) reachable state: After an object is created, more than one referenced variable references it. In a directed graph, you can navigate from the starting vertex to the object, so that it is reachable.

2) recoverable state: if an object in the program no longer has any reference variable to reference it, it will first enter the recoverable state, in this case, you cannot navigate to this object from the starting vertex of the directed graph. In this state, the system's garbage collection mechanism is ready to recycle the memory occupied by this object. Before the collection, the system will call the finalize () method to clean up resources, if more than one referenced variable references the object after the resource is sorted out, the object becomes reachable again; otherwise, the object enters the inaccessibility state.

3) Inaccessibility: When all the associations of an object are cut off and the finalize () method is called to clean up resources, the object is still not made reachable, then, this object will permanently lose reference and become inaccessibility, and the system will actually recycle the resources occupied by this object.

The following figure shows the conversion of the preceding three states:

2. Four types of references to objects in Java

1) strong reference: Create an object and assign it directly to a variable. For example: Person person = new Person ("sunny"); no matter the system resources are insufficient, strongly referenced objects will never be recycled, even if they will not be used later.

2) soft reference: implemented through the SoftReference class. For example: SoftReference <Person> p = new SoftReference <Person> (new Person ("Rain "));, when the memory is very tight, it will be recycled. Otherwise, it will not be recycled. Therefore, before using it, you must determine whether it is null to determine whether it has been recycled.

3) Weak reference: implemented through the WeakReference class. For example: WeakReference <Person> p = new WeakReference <Person> (new Person ("Rain"); no matter whether the memory is sufficient, system garbage collection is required.

4) Virtual Reference: it cannot be used independently. It is mainly used to track the state of the object being reclaimed by garbage collection. The PhantomReference class and the reference queue ReferenceQueue class are used in combination. For example:

123456789101112131415161718192021222324252627 packagetest;  importjava.lang.ref.PhantomReference; importjava.lang.ref.ReferenceQueue;  publicclassTest{      publicstaticvoidmain(String[] args) {         // Create an object         Person person = newPerson("Sunny");            // Create a reference queue         ReferenceQueue<Person> rq = newReferenceQueue<Person>();         // Create a virtual reference to reference this virtual reference to the person object         PhantomReference<Person> pr = newPhantomReference<Person>(person, rq);         // Cut off the person reference variable and Object Reference         person = null;         // Try to retrieve the object referenced by the Virtual Reference         // The program cannot access the referenced object through virtual references. Therefore, the output here is null.         System.out.println(pr.get());         // Force garbage collection         System. gc (); // prompt jvm to perform garbage collection. It is jvm's intention to continue garbage collection.         System. runFinalization (); // force the finalize () method of all non-referenced objects to clean up resources. If more than one referenced variable references the object after the resources are sorted, the object changes to the reachable state again; otherwise, the object enters the inaccessibility state. The Inaccessible status will be recycled by the system.         // Once the object in the Virtual Reference is recycled, the Virtual Reference will enter the reference queue.         // Therefore, use the queue to first enter the queue for reference and pr comparison, and Output true         System.out.println(rq.poll() == pr);     } }

Running result:

3. Java garbage collection mechanism

Java garbage collection mainly involves two tasks: 1) memory collection 2) fragment

3.1 garbage collection Algorithm

1) Serial collection (only one CPU) and parallel collection (multiple CPUs are useful): Serial collection always uses only one CPU to perform garbage collection regardless of the number of CPUs in the system, parallel collection is to split the entire collection into multiple parts, each of which is under the responsibility of one CPU, so that multiple CPUs can be recycled in parallel. Parallel collection is very efficient, but the complexity increases, and there are also some side effects, such as the random increase in memory.

2) Concurrent execution and application Stop: as the name suggests, the Stop-the-world method of the application will cause the application to be suspended when garbage collection is executed. Concurrent execution of garbage collection does not cause application suspension, but because concurrent execution of garbage collection needs to resolve conflicts with application execution (the application may modify objects during garbage collection ), therefore, the system overhead for concurrent execution of garbage collection is higher than Stop-the-world, and more heap memory is required for execution.

3) compression and non-compression and replication:

① The Garbage Collector that supports compression (mark-compression = Mark Clear + compression) will move all reachable objects together, and then all the previously occupied memory will be reclaimed, reducing memory fragmentation.

② The uncompressed garbage collector (mark-clear) needs to traverse twice. For the first time, it first accesses all reachable objects from the beginning and marks them as reachable, the second time, it facilitates the entire memory area and recycles unmarked reachable objects. This recycling method does not compress and does not require additional memory, but it takes two traversal times to generate fragments.

③ Copy-type Garbage Collector: divides the heap memory into two identical spaces and accesses each associated reachable object from the root (similar to the starting vertex of the previous directed graph, copy all reachable objects of space A to Space B, and reclaim space A at A time. For this algorithm, because you only need to access all reachable objects and copy all the reachable objects, the whole space is directly reclaimed, so you don't need to care about the inaccessible objects, therefore, the traversal space cost is small, but it requires a huge copy cost and a large amount of memory.

3.2 heap memory generation collection

1) basis for generational recovery:

① Length of object Survival: Most objects are recycled during Young.

② Different generations adopt different garbage collection strategies: there are few references between new (short-lived) Old (long-lived) Objects

2) heap memory generation:

① Young generation:

I. Recycling mechanism: because the number of objects is small, replication and recycling are adopted.

Ⅱ composition zone: consists of one Eden zone and two vor zones. Two vor zones at the same time are used to save objects, and the other are empty; every time the Young generation recycles garbage, the reachable objects in Eden and From are copied To the To region. Some long-lived objects are copied To the old age, and then the Eden and From spaces are cleared, finally, the original From space is changed To From space, and the original From space is changed To space.

Source of object Ⅲ: Most objects are first allocated to the Eden area, and some large objects are directly allocated to the Old generation.

IV recycling frequency: because most Young objects quickly enter the inaccessible state, the recovery frequency is high and the recovery speed is fast.

② Old generation:

I. Recycling mechanism: Mark compression algorithm is used for recycling.

II object Source: 1. The object size directly enters the old age.

2. Long-lived reachable objects in the Young generation

Ⅲ recovery frequency: because few objects will die, the execution frequency is not high and takes a long time to complete.

③ Permanent generation:

I usage: used to load Class, method, and other information. The default value is 64 MB and will not be recycled.

II object Source: eg: For frameworks like Hibernate and Spring that like AOP dynamic generation classes, a large number of dynamic proxy classes are often generated, so more Permanent memory is needed. Therefore, we often encounter java. lang. OutOfMemoryError: PermGen space errors when debugging Hibernate and Spring. This is the error caused by memory depletion of the Permanent generation.

III recovery frequency: will not be recycled

3.3 common garbage collectors

1) Serial recycler (only one CPU is used): generation Young adopts the serial replication algorithm; Generation Old uses the serial mark compression algorithm (three phases: mark-Clear sweep-compact compression ), during the recycle period, the program will be suspended,

2) Parallel recycler: the algorithms used by the Young generation are the same as those of the serial recycler, but multi-CPU Parallel Processing is added. The processing of the Old generation is exactly the same as that of the serial recycler, and it is still a single thread.

3) Parallel compression recycler: the Young generation adopts the same algorithm as the parallel recycler. It only uses different algorithms for the Old generation, but actually divides different regions, then Mark the compression algorithm:

① Divide the Old generation into several fixed regions;

② Mark stage (multi-thread parallel), marking reachable objects;

③ In the summary stage (serial execution), the test starts from the leftmost to find an area that reaches a value (the object density is small), and the area on the right and the area on this area are compressed and recycled, its left side is dense area

④ The compact phase (multi-thread parallel) identifies the areas to be loaded, and the multi-thread parallel copies the data to these areas. After this process, the Old generation end has a large number of active objects, while the other end has a large space.

4) Concurrent identification-cleaning and recycling (CMS): the Young generation adopts the same algorithm as the parallel recycler, but uses different algorithms for the Old generation, but in the final analysis, the algorithm is marked as follows:

① Initial identifier (Program suspension): Mark the objects directly referenced (level-1 objects );

② Concurrent identification (program running): searches for other reachable objects through a level-1 object;

③ Re-mark (Program pause): objects that may be missed due to concurrency before the re-mark of multi-thread parallel (in short, it is to prevent omission)

④ Concurrent cleaning (program running)

4. Memory Management Tips

1) try to use the direct quantity. For example: String javaStr = "The Growth Course of the apprentice ";

2) use StringBuilder and StringBuffer for string connection and other operations;

3) Release useless objects as soon as possible;

4) Use as few static variables as possible;

5) Common cache objects: they can be implemented using open-source caches, such as OSCache and Ehcache;

6) Try not to use the finalize () method;

7) when necessary, you can consider using soft reference SoftReference.

Related Article

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.