Java garbage Collection (i)

Source: Internet
Author: User

Java garbage Collection (i)

In Java, its memory management consists of two aspects: memory allocation and memory recycling , both of which are done automatically by the JVM, reducing the learning difficulty of Java programmers and avoiding the danger of direct manipulation of memory like C/s + +. But this also makes many programmers do not care about memory allocation problems, resulting in many programs inefficient memory.

The Java language Specification does not explicitly describe which garbage collection algorithm the JVM uses. Commonly used algorithms have the following types:

    1. Reference notation (Reference counting Collector)
    2. Tracing algorithm (tracing Collector)
    3. Compacting algorithm (compating Collector)
    4. Copying algorithm (cpoing Collector)
    5. Generation algorithm (Genrational Collector) is the generation of recycling
    6. Adaptive algorithm
1.Java in-memory state

Let's start by looking at an example:

Person.java

package test;import java.io.Serializable;public class Person implements Serializable {static final long serialVersionUID = 1L;String name; // 姓名Person friend;    //朋友public Person() {}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;}}

The object reference in the main aspect of the above Test.java is drawn as an object reference graph that starts with the main method (vertices are objects and references, and there is a reference relationship to the edge):

When the program is running, it can be divided into three types after the state of the memory is considered as a forward graph:

    1. Up to state : After an object is created, there is more than one reference variable associated with it, then it is in a state of reach.
    2. Recoverable State : If an object in the program no longer has a reference variable associated with it, it will first enter the recoverable state, at which point the starting vertex of the graph can no longer navigate to the object, in which case the system's garbage collection mechanism prepares to reclaim the memory occupied by the object before it is reclaimed. The Finalize () method is called to clean up the resource, and if the resource is organized to re-associate more than one reference variable with the object, the state of the object becomes reachable again, or it enters the unreachable state.
    3. Unreachable State : When all associations of an object are cut off, and the system calls the Finalize () method to clean up the resource after it has not been made reachable, the object will permanently lose its reference and become unreachable. The system is really going to reclaim the resources that the object occupies.
2.4 types of references to Java objects
  1. Strong Reference : Create an object and assign it directly to a variable reference, eg: no Person person = new Person("sunny"); matter how nervous the system resources are, it will never be recycled.
  2. Soft Reference : implemented by the SoftReference class, eg: softreference<person> p = new softreference< Person> ("Rain"); the memory is recycled when it is very tense, and it is not recycled at other times, so it is important to determine if it has been recycled before use. For example:

      class AB {protected void Finalize () {System.out.println ("Finalize .....");}}            public class Javatest {public static void main (string[] args) {for (int i=0; i < 10000; i + +) {        New Softreference<ab> (New AB ()); The result is: Finalize.....finalize.....finalize ..... The result is not necessarily, looking at a personal computer, or there may be no output, you need to create more objects to force the JVM to reclaim soft references. 
  3. Weak reference : implemented by the WeakReference class, eg: weakreference<person> p = new weakreference< Person> (New person ("Rain")); The system garbage collection must be recycled, regardless of the memory adequacy.

      class AB {protected void Finalize () {System.out.println ("Finalize ..."); }}public class Javatest {public static void main (string[] args) {weakreference<ab> wr = new Weakreferenc        E<ab> (New AB ());    System.GC (); The result of the output is: Finalize ..... Forced garbage Collection, if the reference is directly recycled  
  4. Virtual Reference : cannot be used alone, mainly to track the state of the object being garbage collected. The implementation is implemented jointly using the Phantomreference class and the reference queue Referencequeue class, as in the following example.

    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");
    Create a reference queue
    Referencequeue RQ = new Referencequeue ();
    Create a virtual reference to refer to the person object for this virtual reference
    Phantomreference PR = new Phantomreference (person, RQ);
    Cut off a reference to a person reference variable and object
    person = null;
    An attempt was made to remove an object referenced by a virtual reference
    The discovery program does not access the referenced object through a virtual reference, so the output here is null
    System.out.println (Pr.get ());
    Forced garbage Collection
    System.GC ();
    System.runfinalization ();
    Because once the object in the virtual reference is reclaimed, the virtual reference goes into the reference queue
    So use the first queue in the queue to compare the reference with the PR, output true
    System.out.println (rq.poll () = = PR);
    }
    }
    The output is: null true

3. Garbage collector classification
    1. Serial Reclamation (one CPU only) and parallel recycling (multiple CPUs are used): Serial recycling 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 being split into parts, each of which is the responsibility of the CPU, This allows multiple CPUs to be recycled in parallel. Parallel recovery is highly efficient, but the complexity increases, and there are some side effects, such as increased memory fragmentation.
    2. concurrent execution and application stop : Application Stop (Stop-the-world), which causes the application to pause while its garbage collection is executing. While garbage collection that executes concurrently does not cause an application to be paused, because of the need to perform an application-side garbage collection (which might modify the object at the time of recycling, and therefore conflict with the execution of the application), the concurrent execution is more expensive than stop-the-world and requires more heap memory.
    3. Compression and non-compression and replication

      • A compression-enabled garbage collector ( tag-compression = clear + compact ) will move all the available objects to one end, and then directly clean out the memory outside the boundary, reducing memory fragmentation.
      • The garbage collector ( mark-purge ) that does not support compression is traversed two times, first accessed from the root, marks all reachable objects, and iterates through the entire memory area for the second time, reclaiming the objects that are tagged to the state. This method of recycling does not compress and requires no additional memory, but it needs to traverse two times to produce fragmentation.
      • replicated garbage collector: Divides heap memory into two identical controls, accesses each reachable object from the root, copies all reachable objects of A to B space, and reclaims all a spaces at once. The cost of traversing space is small and does not produce fragmentation, but requires huge replication costs and more memory.
4. Memory Management Tips
    1. Use direct quantities as much as possible. eg:string s = "Hello World";
    2. The use of StringBuilder and StringBuffer for string connection and other operations;
    3. Releasing useless objects as early as possible;
    4. use less static variables;
    5. Caching commonly used objects can be implemented with open source, open source caches. Eg:oscache,ehcache;
    6. Try not to use the Finalize () method;
    7. Consider more use of soft drinking softreference when necessary;

Java garbage Collection (i)

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.