Java/android reference types and their usage analysis

Source: Internet
Author: User

There are four types of references in java/android, namely:

Strong reference-strong references
Soft Reference-Soft reference
Weak Reference-Weak references
Phantom Reference-Virtual reference

Different reference types have different characteristics, and they also correspond to different usage scenarios.

1.Strong Reference-strong reference

One of the most common reference types in actual coding. Common forms such as: a A = new A (); The strong reference itself is stored in the stack memory, and its storage points to the address of the object in memory. In general, when a strong reference to an in-memory object no longer points to it, the garbage collection machine begins to consider a possible garbage collection of this memory. For example, when encoding: a = null, at this point, there is no other reference to the new a object that has just been assigned an address in the heap, and the heap memory is garbage collected when the system is garbage collected.

SoftReference, WeakReference, phantomreference are subclasses of class java.lang.ref.Reference. Reference, as an abstract base class, defines the basic operations of its subclass objects. Reference subclasses have the following characteristics:
1.Reference subclasses cannot be directly created without a parameter, and must create their own subclass objects with at least the strong reference object as the construction parameter;
2. Because the object is created in 1 with a strong reference object as a construction parameter, the object in the heap memory pointed to by the original strong reference will no longer be directly associated with the strong reference itself, but also with reference to the subclass object of the reference. This link may affect the object's garbage collection.

According to different sub-class objects, they have different effects on garbage collection, which indicates that the object (the object in the heap in which the strong reference is pointing), respectively, formed three subclasses, namely SoftReference, WeakReference and Phantomreference.

2.Soft Reference-Soft reference

The general use form of soft references is as follows:
A = new A ();
softreference<a> SrA = new softreference<a> (A);

A SoftReference object is created with a strong reference to the object, and the WRA in the stack memory points to the object.

At this point, make the following code: A = null, what is the effect of garbage collection on the A object to which A is originally directed?

First look directly at the output of the following program:

1 Importjava.lang.ref.SoftReference;2 3  Public classReferencetest {4 5      Public Static voidMain (string[] args) {6 7A A =NewA ();8         9Softreference<a> SrA =NewSoftreference<a>(a);Ten  OneA =NULL; A  -         if(Sra.get () = =NULL) { -System.out.println ("A object is recycled"); the}Else { -System.out.println ("A object has not been recycled" +sra.get ()); -         } -  +         //Garbage Collection - System.GC (); +  A         if(Sra.get () = =NULL) { atSystem.out.println ("A object is recycled"); -}Else { -System.out.println ("A object has not been recycled" +sra.get ()); -         } -  -     } in } -  to classA { +  -}

# #输出结果为:

1 A object has not been recycled [email protected] 2 A object has not been recycled [email protected]

When a = NULL, the A object in heap memory will no longer have any strong references to it, but at this point the object that exists in the SRA reference points to the A object. This is well understood when the first call to the Sra.get () method returns this indicator object, because the garbage collector is likely to have not yet been garbage collected, at which point the get () is a result. When the program executes System.GC (); After forcing the garbage collection, through Sra.get (), it is found that the indicated a object is still available, stating that the A object is not garbage collected. So, when does the object indicated by the soft reference start being garbage collected? The following two conditions need to be met:

1. When its indicated object does not have any strong reference to the object pointing to it;

2. When the virtual machine is low on memory.

As a result, thesoftreference in disguise extends the time it indicates that the object occupies heap memory until the garbage collector reclaims this heap memory space until the virtual machine has insufficient memory.

3.Weak Reference-Weak reference

Similarly, the general use of soft references is as follows:
A = new A ();
weakreference<a> WrA = new weakreference<a> (A);

What is the nature of garbage collection when there is no strong reference to this object?

1 Importjava.lang.ref.WeakReference;2 3  Public classReferencetest {4 5      Public Static voidMain (string[] args) {6 7A A =NewA ();8 9Weakreference<a> WrA =NewWeakreference<a>(a);Ten  OneA =NULL; A  -         if(Wra.get () = =NULL) { -System.out.println ("A object is recycled"); the}Else { -System.out.println ("A object has not been recycled" +wra.get ()); -         } -  +         //Garbage Collection - System.GC (); +  A         if(Wra.get () = =NULL) { atSystem.out.println ("A object is recycled"); -}Else { -System.out.println ("A object has not been recycled" +wra.get ()); -         } -  -     } in  - } to  + classA { -  the}

# #输出结果为:

A object has not been recycled [email Protected]a object is recycled

The first result of the output is explained in the same way. When garbage collection occurs, wra.get () returns NULL, indicating that the object has entered the garbage collection process. Therefore, the characteristics of weak references are summarized as:

WeakReference does not change the garbage collection time of the original strongly referenced object, and once it indicates that the object does not have any strongly referenced objects, the object enters the normal garbage collection process.

Well, according to this characteristic, there is probably doubt: what is the meaning of weakreference existence?

Its main usage scenario is that there are currently strong references to strong reference objects, and because of the business need to increase the reference to this object, but also do not want to change the garbage collection time of this reference, at this time WeakReference exactly meet the requirements, common in some and life cycle scenarios.

Here's a scenario for WeakReference used in Android-combining static internal classes and WeakReference to address possible handler memory leaks in your activity.

In activity we need to create a new thread to fetch the data, using the Handler-sendmessage method. The following is a general code for this process:

1  Public classMainactivityextendsActivity {2 3     //...4     Private intpage;5     PrivateHandler Handler =NewHandler () {6 7 @Override8          Public voidhandlemessage (Message msg) {9             if(Msg.what = = 1) {Ten  One                 //... A  -page++; -}Else { the  -                 //... -  -             } +  -         }; +     }; A  at @Override -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); -  -         //... in  -         NewThread (NewRunnable () { to @Override +              Public voidrun () { -                 //..  theMessage msg =Message.obtain (); *Msg.what = 1; $                 //msg.obj = xx;Panax Notoginseng handler.sendmessage (msg); -             } the }). Start (); +  A         //... the  +     } -  $}

Run Link in Eclispe, you will see the warning message: This Handler class should is static or leaks might occur ... Click to view this information, the details of which explain the problem and give a suggested solution.

 issue:ensures that Handler classes A reference to an outer classid:handlerleaksince this Handler are declared as an inner class , it may prevent the OU ter class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread and other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follow S:declare the Handler as a static Class;  in the outer class, instantiate a weakreference to the outer class and pass this object to Y Our Handler If you instantiate the Handler; Make all references to the outer class using the WeakReference object.   

In General, it is recommended that handler be defined as an internal static class, and that in this static inner class you define a a reference to the WeakReference, as indicated by an external activity object.

Problem Analysis:

Activity has its own life cycle, the activity in the new open thread running process, the user may have pressed the back key, or the system is out of memory, and so want to reclaim this activity, Because the new thread in the activity does not follow the activity itself, that is, when activity executes OnDestroy, due to the presence of threads and handler Handlemessage, Makes the system want to do this activity memory recycling cannot be implemented, because non-static inner classes implicitly hold the reference to the external class, resulting in a possible memory leak problem.

Therefore, when using handler in Activity, it is necessary to define it as a static inner class form, which allows it to decouple from the external class (Activity) and no longer hold references to external classes. At the same time, since Handlermessage in handler generally needs to access or modify the properties of the activity, it is necessary to define a weakreference within handler that points to this activity. So that it does not affect the activity's memory collection at the same time, the properties of the activity can be accessed under normal circumstances.

Not to be continued ...

Java/android reference types and their usage analysis

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.