Graphics and text detailed Java memory recycling mechanism _java

Source: Internet
Author: User
Tags compact garbage collection

In Java, its memory management consists of two aspects: memory allocation (when creating Java objects) and memory recycling, both of which are done automatically by the JVM, reducing the learning difficulties of Java programmers and avoiding the risk of direct manipulation of memory like C + +. However, because memory management is entirely the responsibility of the JVM, so many Java programmers are no longer concerned about memory allocation, resulting in many programs inefficient, memory consumption. So there is a Java programmer who should finally understand the JVM in order to write programs that are more efficient and take full advantage of limited memory.

1.Java in-memory state

First we write a code as an example:
Person.java

Package test;

Import java.io.Serializable;

public class Person implements Serializable {
  static final long serialversionuid = 1L;
  String name; Name person
  friend;  Friend Public Man
  () {} public person
  (String name) {
    super ();
    this.name = name;
  }
 

Test.java

 Package test;

public class test{public

  static void Main (string[] args) {person
    p1 = new Person ("Kevin");
    person P2 = new Person ("Rain");
    Person P3 = new Person ("Sunny");

    P1.friend = p2;
    P3 = p2;
    P2 = null;
  }
} 

This is the case for drawing an object reference from the main aspect of the above Test.java to an object reference diagram starting with the main method (vertices are objects and references, and there are references to edges):


When the program is run, it can be divided into three types after it is viewed as a graph in memory:

1 up to state: After an object is created, there is more than one reference variable referencing it. In a direction diagram, you can navigate from the starting vertex to the object, and it is in a state of reach.

2 recoverable state: If an object in the program no longer has any reference variables to reference it, it will enter a recoverable state, at which point the starting vertex of the direction graph can no longer navigate to the object. In this state, the system's garbage collection mechanism prepares to reclaim the memory occupied by the object, and before recycling, the Finalize () method is called for resource cleanup, and if the resource is collated to allow more than one reference variable to refer to the object, the object becomes reachable again. , otherwise it will enter an unreachable state.

3) Not up to the state: when all the associations of an object are cut off and the system calls the Finalize () method to clean up the resource without making the object reachable, the object will permanently lose its reference and become an unreachable state, and the system will actually reclaim the resources it occupies.

The conversion diagram of the above three states is as follows:


2.Java 4 kinds of references to objects

1 Strong reference: Create an object and assign the object directly to a variable, eg:person person = new Person ("Sunny"); No matter how nervous the system resources are, strongly referenced objects will never be recycled, even if they are never used again.

2) Soft Reference: Implement,eg:softreference<person> p = new softreference<person> (New person ("Rain") by SoftReference class; Memory is recycled when it is very tense, and will not be reclaimed at other times, so determine if it is null before using it to determine if he has been recycled.

3) Weak reference: Implement,eg:weakreference<person> p = new weakreference<person> (New person ("Rain") by WeakReference class; System garbage collection is bound to be recycled, regardless of whether the memory is adequate.

4) Virtual reference: cannot be used alone, primarily to track the state of the object being garbage collected. Implemented using Phantomreference class and reference queue Referencequeue class, eg:

 Package test;

Import java.lang.ref.PhantomReference;
Import Java.lang.ref.ReferenceQueue;

public class test{public

  static void Main (string[] args) {
    //Create an object person person
    = new Person ("Sunny"); 
   
    //creates a reference queue  
    referencequeue<person> RQ = new referencequeue<person> ();
    Creates a virtual reference that refers to the person object
    phantomreference<person> PR = new phantomreference<person> (person, RQ);
    Cut off the person reference variable and the object's reference person
    = null;
    An attempt to remove an object/Discovery program referenced by a virtual reference
    cannot access the referenced object through a virtual reference, so the output here is null
    System.out.println (Pr.get ());
    Compulsory garbage collection
    System.GC ();
    System.runfinalization ();
    Because once an object in a virtual reference is reclaimed, the virtual reference goes into the reference queue
    //So the first entry into the queue in the queue is compared to PR, and the output is true
    System.out.println (rq.poll () = PR);
  }
} 


   

Run Result:


3.Java garbage collection mechanism

In fact, Java garbage collection mainly do two things: 1 Memory Recycling 2 defragmentation

3.1 Garbage collection algorithm

1 Serial recovery (one CPU only) and parallel recycling (multiple CPUs are available): A serial collection is a garbage collection operation that is always performed with only one CPU regardless of the number of CPUs in the system, while a parallel recycle is the entire collection split into parts, each of which is owned by one CPU, Thus allowing multiple CPUs to be recycled concurrently. The execution of parallel recycling is efficient, but the complexity increases, and there are some side effects, such as a casual increase in memory.

2 Concurrent execution and application stop: Application Stop (Stop-the-world) as the name suggests, its garbage collection method can cause application pauses while performing garbage collection. Concurrent garbage collection does not cause application pauses, but because concurrent execution of garbage requires resolution and application execution conflicts (applications may modify objects in the process of garbage collection), the system overhead of concurrent garbage collection is higher than Stop-the-world, And more heap memory is required for execution.

3 compression and no compression and replication:

① support for compressed garbage collector (Tag-compress = Mark Clear + compression) will move all the accessible objects together, and then reclaim all the memory previously consumed, reducing memory fragmentation.

② Uncompressed garbage collector (mark-purge) to traverse two times, the first access to all reachable objects from the start, and mark them as reachable, the second convenience of the entire memory area, the object is not marked up to the state of the recovery process. This method of recycling does not compress, requires no additional memory, but two traversal will result in fragmentation

③-Replicated garbage collector: divides the heap memory into two identical spaces, starting with the root (similar to the preceding direction graph starting vertex) to access each associated reachable object, copying all reachable objects of space A to space B, and then reclaiming space A at a lump-sum. For this algorithm, because only access to all reachable objects, all the reachable objects will be copied away directly after the entire space, completely ignore the unreachable object, so the cost of traversal space is small, but it requires huge replication costs and more memory.

3.2-Heap memory generation recycling

1) The basis for the collection of recycling:
① Object lifetime: Most objects are recycled during young
② different generations take different garbage collection strategies: New (short lifetime) old (long live) objects rarely have references between

2) heap memory of the generational:

①young Generation:
Ⅰ Recycle mechanism: Because the number of objects is small, replication recycling is used.
Ⅱ: Consisting of 1 Eden and 2 survivor, two survivor of the same time, one for holding objects and the other for being empty, and for each young generation of garbage collection, the Eden,from can be copied into the to region, Some survival time is copied to the old age, then clear eden,from space, and finally the original to space into from space, the original from space into to space.
Ⅲ Object Source: Most objects are assigned to the Eden area first, and some large objects are assigned directly to the old generation.
Ⅳ Recovery frequency: Because young generation object most quickly enters the unreachable state, therefore the recovery frequency is high and the recovery speed is fast

②old Generation:
Ⅰ recovery mechanism: The use of labeling compression algorithm recycling.
Ⅱ Object Source: 1. The object of the large direct entry into the old age.

A long life-time accessible object in the 2.Young generation
Ⅲ Recovery frequency: Because very few objects die, the execution frequency is low and takes a long time to complete.
③permanent Generation:
Ⅰ use: Used to load class, methods and other information, the default is 64M, will not be recycled
Ⅱ object Source: Eg: for frameworks like Hibernate,spring, which like AOP dynamically generated classes, a large number of dynamic proxy classes are often generated, so more permanent memory is needed. So we often encounter Java.lang.OutOfMemoryError:PermGen space error when debugging hibernate,spring, which is the error caused by permanent memory exhaustion.
Ⅲ Recovery frequency: will not be recycled

3.3 Common Garbage Collector

1 Serial collector (using only one CPU): Young generation uses the serial replication algorithm, the old generation uses the serial marking compression algorithm (three stages: The Mark mark-clears the sweep-compact), the procedure will produce the pause during the recycle,

2 Parallel collector: The algorithm used by young generation and serial collector, just like the addition of multiple CPU parallel processing, the old generation of processing and serial collector exactly the same, is still a single thread.

3) Parallel compression collector: for young generation processing using the exact same algorithm as the parallel collector, but for the old generation using a different algorithm, in fact, is divided into different regions, and then the labeling compression algorithm:

① the old generation into several fixed regions;
②mark phase (multithreading parallel), marking up to the object;
③summary phase (serial execution), starting at the far left. When you find an area that reaches a value (up to the density of the object), the area and its right region are compressed and collected, and the left end is a dense area
The ④compact phase (multithreading parallelism) identifies areas that need to be loaded, and multithreading replicates data to these areas in parallel. After this process, there is a large number of active objects at one end of the old generation and large space on the other end.

4 Concurrent identification-clean up (CMS): The young generation processing using the same as the parallel collector algorithm, but only for the old generation using a different algorithm, but in the final place or the tag cleanup algorithm:

① Initial identity (program paused): tags are directly referenced objects (first-level objects);
② Concurrent Identification (program operation): To find other accessible objects through the first class object;
③ (Program paused): multithreaded parallel tagging of objects that may have been missed by concurrency (simply to prevent omission)
④ Concurrency Cleanup (program run)

4. Memory Management Tips

1) Use direct quantity as far as possible, eg:string javastr = "The growth course of small apprentice";
2) using StringBuilder and StringBuffer to carry out string concatenation operation;
3 Release the useless object as soon as possible;
4 The use of static variables as little as possible;
5 cache commonly used objects: can use open source of open source cache implementation, Eg:oscache,ehcache;
6) Try not to use the Finalize () method;
7 You may consider using soft reference softreference when necessary.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.