Summary of Java References

Source: Internet
Author: User
Tags garbage collection stub thread tostring java reference

Strongreference, SoftReference, WeakReference, Phantomreferencejava quotes summary--strongreference, SoftReference, WeakReference, Phantomreference

1 Introduction to Java references

Java introduced 4 references starting with the 1.2 version, and the levels of these 4 references are from high to low:

Strong references > Soft references > Weak references > virtual references

⑴ Strong reference (Strongreference)
Strong references are the most common references used. If an object has a strong reference, the garbage collector will never reclaim it. When memory space is low, the Java virtual machine would rather throw a outofmemoryerror error, cause the program to terminate abnormally, and not recycle the strongly referenced object to solve the out-of-memory problem.

⑵ Soft Reference (SoftReference)

If an object has only a soft reference, the memory space is sufficient, the garbage collector will not recycle it, and if the memory space is low, the memory of those objects is reclaimed. The object can be used by the program as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive caching.

A soft reference can be used in conjunction with a reference queue (Referencequeue), and the Java Virtual machine will add the soft reference to the reference queue associated with it if the object referenced by the soft reference is reclaimed by the garbage collector.

⑶ Weak reference (WeakReference)

A weak reference differs from a soft reference in that an object that has only a weak reference has a more ephemeral lifecycle. When the garbage collector thread scans the area of memory it governs, it reclaims its memory whenever it discovers an object that has only a weak reference, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a very low priority thread, it is not necessarily easy to find those objects that have only weak references.

A weak reference can be used in conjunction with a reference queue (Referencequeue), and the Java virtual machine adds the weak reference to the reference queue associated with it if the object referenced by the weak reference is garbage collected.

⑷ Virtual Reference (phantomreference)

"Virtual Reference" as the name suggests, is a fake, and several other references are different, the virtual reference does not determine the life cycle of the object. If an object holds only a virtual reference, it is likely to be reclaimed by the garbage collector at any time, as without any reference.

Virtual references are used primarily to track activities that objects are reclaimed by the garbage collector. One difference between a virtual reference and a soft reference and a weak reference is that a virtual reference must be used in conjunction with a reference queue (Referencequeue). When the garbage collector is ready to reclaim an object, if it finds a virtual reference, it adds the virtual reference to the associated reference queue before reclaiming the object's memory.

Because references and memory recycling are closely related. Below, we have an understanding of memory recycling through an instance, and then further deepen the understanding of references by referencing instances.

2 Memory Recovery

Create a public class mydate, which is to overwrite the Finalize () function: Print information in Finalize () to facilitate tracking.

Description: The Finalize () function is executed when the JVM reclaims memory, but the JVM does not guarantee that finalize () will be invoked when memory is reclaimed.

The MyDate code is as follows:

Package Com.skywang.java;
     
Import java.util.Date;
     
public class MyDate extends Date { 
     
    /** creates a new instance of MyDate *
    /Public mydate () {
    }
    //Overwrite Finali The Ze () method
    protected void Finalize () throws Throwable {
        super.finalize ();
        System.out.println ("obj [Date:" + this.gettime () + "is GC");
    }   
     
    Public String toString () {return
        "Date:" + this.gettime ();
    }
}

In this class, the Java.util.Date class is extended and the Finalize () and ToString () methods are overridden.

Create a public class referencetest, which is to define a method Drainmemory (): Consumes a large amount of memory, which causes the JVM to reclaim memory.

The Referencetest code is as follows:

Package Com.skywang.java;
     
public class Referencetest {   
    /** creates a new instance of Referencetest *
    /Public referencetest () {
    }   
         
    // Consumes a large amount of memory public
    static void Drainmemory () {
        string[] array = new string[1024 *;
        for (int i = 0; i < 1024 * i++) {for
            (int j = ' a '; J <= ' Z '; j +) {
                Array[i] + = (char) j;
            }           
        }
    }
}

In this class, a static method Drainmemory () is defined, which is designed to consume a large amount of memory, prompting the JVM to run garbage collection.

With the above two common classes, we can test when the JVM is garbage collected. The following are tested in 3 different scenarios:

Scenario 1: Clear objects

Implementation code:

Package Com.skywang.java;
     
public class Nogarbageretrieve {public
     
    static void Main (string[] args) {
        mydate date = new MyDate ();
        date = null;
    }
}

Run Result:

< no output >

Result Analysis: Date was set to NULL, but MyDate's Finalize () method was not run because the JVM did not perform a garbage collection operation.

Scenario 2: Explicitly invoking garbage collection

Implementation code:

Package Com.skywang.java;
     
public class Explicitgarbageretrieve {
     
    /**
     * @param args
     *
    /public static void main (string[] args) {
        //TODO auto-generated method stub
        MyDate date = new MyDate ();
        date = null;
        System.GC ();
    }
     

Run Result:

obj [date:1372137067328] is GC

Result Analysis: The System.GC () was invoked to enable the JVM to run garbage collection, and the MyDate Finalize () method was run.

Scenario 3: Implicit invocation of garbage collection

Implementation code:

Package Com.skywang.java;
     
public class Implicitgarbageretrieve {
     
    /**
     * @param args
     *
    /public static void main (string[] args) {
        //TODO auto-generated method stub
        MyDate date = new MyDate ();
        date = null;
        Referencetest.drainmemory ();
    }
     

Run Result:

obj [date:1372137171965] is GC

Result Analysis: Although the garbage collection Method System.GC () was not explicitly invoked, the JVM was triggered for garbage collection by running a memory-intensive method.

Summary: The JVM's garbage collection mechanism, in the case of sufficient memory, is not garbage collected unless you explicitly call System.GC (), and garbage collection will run automatically when there is not enough memory

3, Java reference to the classification

3.1 Strong references

Instance code:

Package Com.skywang.java;
     
public class Strongreferencetest {public
     
    static void Main (string[] args) {
        mydate date = new MyDate ();
        System.GC ();
    }

Run Result:

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.