Java strong references, soft references, weak references, virtual references

Source: Internet
Author: User

Using Java how long has not known the original Java has four types of reference, this reference type and we do not normally say the same. The reference type here does not refer to one of the data types, but refers to the four types that are part of the reference in Java. They represent the four strength of the JVM's reclaimed memory, as follows.

Strong references:

References in Java are a bit like pointers to C + +. By reference, you can manipulate objects in the heap. In a function, when an object is created, the object is assigned to the heap, and the object can be manipulated by a reference to that object.

Object O=new object ();

Assuming that the above code is running in the function body, then the local variable o is allocated on the stack, and the object instance is allocated on the heap. The local variable o points to the heap space where the object instance resides, and through O you can manipulate the instance, then O is the reference to object.


If you create an assignment statement again

Object oj=o;
then O point to the object memory space will also be OJ point, at this time we can say oj==o, Then ob.equals is certainly equal, that is, the value of two objects is certainly the same, when the O object is modified, the OJ object will also change, or when the OJ object is modified when the O object will certainly change. So if you want to copy the value of another object, do not use this way, in the case of multi-threaded situations may be more than the case, you can use the JDK's own cloning method, you can also rewrite the cloning method.

public class Test1 {public static void main (string[] args) {Student s=new student ("1", "I am big S"); student s=s; System.out.println (s==s); TrueSystem.out.println (S.equals (s)); TrueSystem.out.println ("Print out large S" +s); Id=1system.out.println ("Print out small S" +s); Id=1s.setid ("2"); SYSTEM.OUT.PRINTLN ("Modified large S" +s);  Id=2system.out.println ("Unmodified small S" +s); Id=2s.setid ("3"); System.out.println ("Unmodified large S" +s); ID=3SYSTEM.OUT.PRINTLN ("Modified small S" +s); Id=3}}class student{string name; String Id;public string GetName () {return name;} public void SetName (String name) {this.name = name;} Public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public student (string name, string id) {super (); this.name = Name;this.id = ID;} @Overridepublic String toString () {return "student [name=" + name + ", id=" + ID + "]";}}




The big S and small s in the example above are strong references, and strong references have the following characteristics:

1. A strong reference can directly access the target object.

2. The object pointed to by a strong reference is not reclaimed by the system at any time. The JVM prefers to throw an oom exception, nor does it reclaim the object that the strong reference points to.

3. Strong references can lead to memory leaks, in order to avoid memory leaks, after the use of the string object is set to NULL, if it is a collection can be used

List list=new arraylist<> (); List.clear ();
Soft References:

The strength of a soft reference is second only to strong references, and if an object has only soft references, enough memory is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. soft references can be used to implement memory-sensitive caches.

We can use Java.lang.ref.SoftReference to create soft references;

String Str=new string ("abc");                                     Strong reference softreference<string> softref=new softreference<string> (str);     Soft references
when memory is low, it is equivalent to:

If (JVM. Insufficient memory ()) {   str = null;  Convert to Soft reference   System.GC ();//garbage collector for recycling}
Weak references:

Weak references are stronger than soft references shepherds, which means that objects with only weak references have a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.

If this object is used occasionally and wants to be available at any time when it is used, but does not want to affect the garbage collection of this object, then you should mark this object with Weak Reference.

String Str=new string ("abc");    weakreference<string> abcweakref = new weakreference<string> (str); str=null;
If you want to turn this object into a strong reference, you can use

String  ABC = abcweakref.get ();

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

When you want to refer to an object, but this object has its own life cycle, you do not want to intervene in the life cycle of this object, you are using weak references.

This reference does not have any additional impact on the object's garbage collection judgment.

public class Referencetest {private static referencequeue<verybig> RQ = new referencequeue<verybig> (); public static void Checkqueue () {reference<? extends verybig> ref = Null;while ((ref = Rq.poll ()) = null) {if (ref ! = null) {System.out.println ("in Queue:" + ((verybigweakreference) (ref)). id);}}} public static void Main (String args[]) {int size = 3; linkedlist<weakreference<verybig>> weaklist = new linkedlist<weakreference<verybig>> (); (int i = 0; i < size; i++) {Weaklist.add (New verybigweakreference (New Verybig ("Weak" + i), RQ)); System.out.println ("Just created weak:" + weaklist.getlast ());} System.GC (); try {//under rest for a few minutes and let the garbage collection thread above run to finish Thread.CurrentThread (). Sleep (6000), catch (Interruptedexception e) {E.printstacktrace ();} Checkqueue ();}} Class Verybig {public String id;//takes up space for thread recycling byte[] B = new byte[2 * 1024x768];p ublic verybig (String id) {this.id = ID;} protected void Finalize () {System.out.println ("finalizing verybig" + ID);}} Class VeRybigweakreference extends weakreference<verybig> {public String id;public verybigweakreference (VeryBig big, Referencequeue<verybig> RQ) {super (big, RQ); this.id = Big.id;} protected void Finalize () {System.out.println ("finalizing verybigweakreference" + ID);}}
Virtual Referencea virtual reference is, by definition, a dummy, a virtual reference , also known as a phantom reference: an object that has a virtual reference does not have an effect on the time to live, or a virtual reference to a real reference to an object. The only use: to be able to receive the system notification when the object is GC, using Phantomreference in Java to implement the virtual reference. Compare Different:

Class Grocery {private static final int SIZE = 10000;//Property D makes each grocery object occupy more memory, 80K or so private double[] D = new Double[size] ;p rivate String Id;public Grocery (string id) {this.id = ID;} Public String toString () {return ID;} public void Finalize () {System.out.println ("About to reclaim" + ID);}} public class References {private static referencequeue<grocery> RQ = new referencequeue<grocery> ();p ublic static void Checkqueue () {reference<? extends grocery> inq = Rq.poll ();//Remove a reference from the queue if (inq! = null) System.out.prin TLN ("In queue:" + inq + ":" + inq.get ());} public static void Main (string[] args) {final int size = 10;//Create 10 grocery objects and 10 soft references set<softreference<grocery> > sa = new hashset<softreference<grocery>> (); for (int i = 0; i < size; i++) {Softreference<grocery&gt ; ref = new Softreference<grocery> (New grocery ("soft reference" + i), RQ); System.out.println ("Just created:" + ref.get ()); Sa.add (ref);} System.GC (); Checkqueue ();//create 10 grocery objects and 10 weak references Set<weakreferencE<grocery>> wa = new hashset<weakreference<grocery>> (); for (int i = 0; i < size; i++) {Weakreferen Ce<grocery> ref = new Weakreference<grocery> (New grocery ("weak reference" + i), RQ); System.out.println ("Just created:" + ref.get ()); Wa.add (ref);} System.GC (); Checkqueue ();//create 10 Grocery objects and 10 virtual references set<phantomreference<grocery>> PA = new hashset< Phantomreference<grocery>> (); for (int i = 0; i < size; i++) {phantomreference<grocery> ref = new Phantom Reference<grocery> (New Grocery ("ABC" + i), RQ); System.out.println ("Just created:" + ref.get ());p a.add (ref);} System.GC (); Checkqueue ();}}
in the above example, 10 10 soft references, 10 weak references, and 10 virtual references are created sequentially, each referencing a grocery object. And the GC method is called after creation. from the printing results when the program runs, it can be seen that the virtual reference is a dummy, the object it refers to can be garbage collected at any time, the object with weak reference has a slightly long life cycle, when the garbage collector performs the recycling, it is possible to garbage collection, the object with soft reference has a longer life cycle, However, in the case of a Java virtual machine that is considered out of memory, it is also garbage collected.

SummaryStrong quote: Like the Boss (OOM) son, in the company can do nothing, but do not always occupy the company's resources for his own work, remember to use the company's sister, to let them go to work (resources to understand release) or the company will likely collapse.
Soft quotes: A bit like a relative of the Boss (OOM), who may be expelled from the company, even if you complain that he (called a GC) goes to work, but as long as he is not seen by the boss (detected by the JVM), it will not be fired (by a virtual machine).
Weak reference: is an ordinary employee, usually if poor performance will be expelled ( the object has no other reference ), encountered other people complain (call GC) to work to see the film, The dismissal is affirmative (by the virtual machine recycling).
Virtual reference: This is estimated to be an intern and temporary workers, when things come to think of you, no matter when, seconds seconds to take out the top pot, expelled.








Java strong references, soft references, weak references, virtual references

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.