Cache processing in Android

Source: Internet
Author: User

First, the cache introduction

(a), the need for caching in Android:

1, there is no cache of the drawbacks:

    • Traffic overhead: For clients-server-side applications, it is often a function to get pictures remotely, and picture resources tend to consume larger volumes of traffic.

    • Loading speed: The user experience can be very bad if the picture in the app is loaded slowly.

    • So how to deal with the acquisition and management of image resources? Asynchronous download + Local cache

2, the benefits of caching:

    • 1. The server pressure is greatly reduced;

    • 2. The client responds much faster (user experience is good);

    • 3. The client's data loading error situation is much less, greatly improved the stability (user experience good);

    • 4. You can support offline browsing (or technical support for offline browsing) to a certain extent.

3. Application Scenarios of cache management:

    • 1. Provide the application of network service;

    • 2. The data update does not need to be updated in real time, even if the 3-5-minute delay is recommended.

    • 3. The expiration time of the cache is acceptable (not due to the benefits of the cache, resulting in some data due to the update less than the impact of the image of the product, etc.)

4. What is the reason why large bitmaps cause large memory overhead?

    • 1. The process of downloading or loading is prone to blocking;

    • The large bitmap Bitmap object is 30 to 100 times times the image of the PNG format;

    • 2. The decoding process of the large bitmap before it is loaded into the ImageView control; bitmapfactory. DecodeFile () will have memory consumption. (Decodebytearray ())

5, the key points of the cache design:

    • 1. Hit rate;

    • 2. Reasonable allocation of occupied space;

    • 3. A reasonable level of caching.

(b), the correct process to load the picture is: "Memory-file-Network layer three cache policy"

1, first from the memory cache, take the return, not to take the next step;

2, from the file cache, take the return and update to the memory cache, the next step is not taken;

3, download pictures from the network, and update to the memory cache and file cache.

Specifically, the same picture is taken from the network once, then cached locally, and then loaded from the cache when the same image loads. Reading pictures from the memory cache is the fastest, but because the memory capacity is limited, it is best to add the file cache. The file cache space is also not infinite, the larger the capacity, the lower the read efficiency, so you can set a limited size such as 10M, or limit the time to save such as one day.

In a key-value pair (key-value), the image cache key is the hash value of the image URL , and value is bitmap. So, according to this logic, as long as a URL has been downloaded, its picture is cached.

(c), memory cache classification

In previous versions of JDK1.2, when an object was not referenced by any variable, the program could no longer use the object. That is, the program can only use the object if it is in a palpable state. This is like in daily life, after buying a certain item from the store, if it is useful, keep it, or throw it into the garbage bin and collect it from the cleaners. Generally speaking, if the item has been thrown into the dustbin, it is impossible to pick it up again. But sometimes the situation is not so simple, you may encounter a similar chicken like the same items, food tasteless, discard. This kind of thing is useless now, keep it occupied space, but immediately throw it is not cost-effective, because it might come in handy in the future. For such dispensable items, a compromise of the treatment is: if the home space enough, first leave it at home, if the home space is not enough, even if the home of all the rubbish to remove, or can not accommodate those essential necessities of life, then throw away these dispensable items.

Starting with the JDK1.2 version, the object's references are divided into four levels, giving the program more flexibility in controlling the object's life cycle. These four levels are high to low in order: strong references , soft references , weak references , and virtual references .

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6B/F1/wKioL1U7YorzqKksAAAffVDHISM657.gif "title=" C925092176f6.gif "alt=" Wkiol1u7yorzqkksaaaffvdhism657.gif "/>

1, Strong reference : (LRUCache in Android is a strong reference cache )

Usually when we program, for example: Object Object=new object (); That object is a strong reference. If an object has a strong reference, it is similar to essential necessities, and the garbage collector will never recycle it . When there is not enough memory space, the Java virtual Machine prefers to throw an OOM exception that terminates the program and does not reclaim a strongly referenced object to resolve the out-of-memory problem.

2,

Soft references are similar to the dispensable necessities of life. If the memory space is sufficient, the garbage collector does not reclaim 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. A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is garbage collected, the Java Virtual machine will add the soft reference to the reference queue associated with it .

Using soft references can prevent memory leaks and enhance the robustness of the program.


3. Weak references (WeakReference):

The difference between a weak reference and a soft reference is that an object with only a weak reference has 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. 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 reference queue associated with it.

4,

  "virtual reference" as the name implies, is a dummy , unlike several other references, a virtual reference does not determine the life cycle of an object. If an object holds only virtual references, then it is the same as no reference, in at any time. Virtual references An activity that is primarily used to keep track of objects being garbage collected .

One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled.

"Related applications:"

Three classes are available in the Java.lang.ref package: The SoftReference class, the WeakReference class, and the Phantomreference class, which represent soft, weak, and virtual references, respectively. The Referencequeue class represents a reference queue, which can be used in conjunction with these three reference classes in order to track the activity of the object referenced by the Java Virtual machine.

Lru:least Recently used  

The least recently used algorithm , is a page replacement algorithm, the idea is that the number of cached pages are fixed, the most recent use of the least number of pages will be moved out, for our memory cache, the strong reference cache size fixed to 4M, if the cached image is greater than 4M, Some images are removed from the strong reference cache, and the images are deleted, which are the least recently used images.

(iv), memory storage:

In memory, you can only save a certain amount, but not to go to the inside, you need to set the data expiration time, LRU and other algorithms. One way to do this is to put the usual data in a cache (a), and put it in another cache (B) infrequently. When you want to fetch data, get it from a, and then go to b if it doesn't exist. The data in B is mainly from the LRU data in a, where memory recycling is mainly for B memory, so that the data in a can be effectively hit.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6B/F5/wKiom1U7YqKSwu_nAAAzA3ITEEM740.gif "title=" 13135212avm1.gif "alt=" Wkiom1u7yqkswu_naaaza3iteem740.gif "/>

This article is from the "Meu Late injury" blog, please be sure to keep this source http://zzhhz.blog.51cto.com/7107920/1638335

Cache processing in Android

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.