Strong references to Android performance gains, soft references, weak references, virtual references use

Source: Internet
Author: User

Reprint please the head source link and the tail two-dimensional code together reprint, this article from countercurrent fish yuiop:http://blog.csdn.net/hejjunlin/article/details/52637333

Background: Received a public contribution, "Reference from the Interview question (citation)", analysis is very good, total feeling less practical examples and application scenarios. So combined with their own work in the scene, a small summary. Look at the following agenda:

    • Strong references
    • Soft references
    • Weak references
    • When to use soft references, when do you use weak references?
    • Virtual reference
First, strong references

A reference in Java, similar to a C + + pointer. 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.

Assuming that the above code is run within a method, the local variable str is allocated to the stack space, and the object StringBuffer instance, which is allocated in the heap space. The local variable str points to the heap space where the StringBuffer instance resides, and the instance is manipulated by STR, so STR is the StringBuffer reference.

At this point, run an assignment statement:

Then, the object that Str points to will also be pointed to by STR1, while allocating space on the local stack space to hold the STR1 variable. At this point, the StringBuffer instance has two references. the "= =" operation on a reference is used to indicate whether the heap space address pointed to by the two operands is the same, and does not indicate whether the objects pointed to by the two operands are equal.

Strong citation features:

    • A strong reference can directly access the target object.
    • The object that the strong reference points to 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.
    • A strong reference can cause a memory leak.
Second, soft reference

Soft references are the strongest reference types in addition to strong references. Soft references can be used through java.lang.ref.SoftReference. An object that holds soft references will not be recovered by the JVM very quickly, and the JVM will determine when to recycle based on the current heap usage. Soft-referenced objects are recycled when the heap usage is near the threshold.
Look at my work using a soft reference scene, load a 1080x1920 resolution diagram, about 900 k, for us, this figure is very large.

    • First, a large map is constructed by Bitmapfactory.decodestream bitmap
    • Then turn this bitmap into a drawble type and make a strong reference.
    • The soft reference drawables of this Drawable object is then constructed using SoftReference.
    • Finally, a strong reference to the Drawable object instance is obtained through the Get () method of the soft reference, and the object is not reclaimed. A soft reference object is not reclaimed when the GC is fully memory-rich.

    • In practice, the request for a lot of related pictures, from the network, then will request a very large amount of memory space, resulting in a tight memory, the system began to GC. After this GC, Drawables.get () no longer returns the Drawable object, but returns null, when the background image on the screen is not displayed, indicating that the soft reference is recycled in the case of a system memory shortage.

    • With soft references, the memory space of these cached picture resources can be freed up before the outofmemory exception occurs, preventing the memory from reaching the upper limit and preventing crash from occurring.

    • It should be noted that the Get method provided by the SoftReference class returns a strong reference to the Java object before the garbage collector reclaims the Java object, and once the garbage thread reclaims the Java object, the Get method returns NULL. So in the code that gets the soft reference object, be sure to determine whether it is null in case the NullPointerException exception causes the application to crash.

When to use soft references, when do you use weak references?

Personally, if you just want to avoid outofmemory exceptions, you can use soft references. If you are more concerned about the performance of your application and want to reclaim some objects that occupy large memory as soon as possible, you can use weak references.

There is also can be based on whether the object is often used to judge. If the object is likely to be used frequently, use soft references as much as possible. If the object is more likely to be used, a weak reference can be used.

In addition, Weakhashmap is similar to the weak reference function. Weakhashmap for a given key, the presence of its mappings does not prevent the garbage collector from reclaiming the key, and its entries are effectively removed from the map after recycling. Weakhashmap uses Referencequeue to implement this mechanism.

Third, weak references

A weak reference is a reference type that is weaker than a soft reference. In a system GC, objects are recycled whenever a weak reference is found, regardless of the adequacy of the system heap space. However, because the garbage collector thread usually has a low priority, it can quickly find objects that hold weak references. In this case, the weak reference object can exist for a longer period of time. Once a weak reference object is reclaimed by the garbage collector, it is added to a registration reference queue.
See a working example: Player play panel, is a view, is in the video playback, you can show, hide, you can also drag the progress bar, and the above volume, brightness adjustment and so on. Such a view, we use weak reference, because in the video playback process, whether hard or soft solution, will occupy a lot of memory. Make sure the video is rendered visually.
The following section of code is in Videocontrollerview.java:

The weak reference object was not discovered by the garbage collector before the GC, so the corresponding strong reference could be obtained by the Mview.get () method. However, as soon as a garbage collection is made, the weak reference object is immediately reclaimed and added to the registration reference queue once it is discovered. At this point, a strong reference through the Mview.get () method fails again.

Note: Soft references, weak references, are great for storing those cache data that are not dispensable. If you do this, the cached data is reclaimed when the system is running out of memory and does not cause memory overflow. And when memory resources are plentiful, these cached data can exist for quite a long time.

Four, virtual reference
    • A virtual reference is the weakest of all reference types. An object that holds a virtual reference is almost the same as no reference, and can be reclaimed by the garbage collector at any time. When you try to get a strong reference by a virtual reference, the Get () method always fails. Also, a virtual reference must be used in conjunction with a reference queue, which is designed to track the garbage collection process.
    • When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will destroy the object after garbage collection, and the virtual reference is added to the reference queue.
    • Practically useless, temporarily not introduced.

The final picture summarizes:

The first time to get blog update reminders, as well as more Android dry, source code Analysis , Welcome to follow my public number, sweep the bottom QR code or long press to identify two-dimensional code, you can pay attention to.

If you feel good, easy to praise, but also to the author's affirmation, can also share this public number to you more people, original not easy

Strong references to Android performance gains, soft references, weak references, virtual references use

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.