Android-LruCache source code parsing

Source: Internet
Author: User

Android-LruCache source code parsing

In mobile device development, the use of effective caching technology is necessary because the memory of mobile devices (such as mobile phones) is limited. android provides a cache tool class LruCache, which is often used during development. The following describes how it is implemented.

The package android. util package contains a java file defined for LruCache. To understand LruCache accurately, let's take a look at the original description:

 * A cache that holds strong references to a limited number of values. Each time * a value is accessed, it is moved to the head of a queue. When a value is * added to a full cache, the value at the end of that queue is evicted and may * become eligible for garbage collection.
LruCache caches a certain amount of data by using a strong reference of the data. each time a data is used (obtained), the data will be moved to the header of the (a data storage) queue. When a new data is added to the cache, if the cache is full, the last data in the cache queue is automatically deleted, so that the deleted data is not strongly referenced and can be recycled by gc.

 

From the above translation, we can know how LruCache works. Next we will explain its implementation step by step:

(1)How to save the data is in a certain order, and an existing data is used, the data will be moved to the data queue header. Here we use LinkedHashMap.

We know that LinkedHashMap stores a key-value pair of data and can maintain the corresponding sequence of the data. generally, the stored data is stored in or in the order of use. let's take a look at the construction method of LruCache:

Public LruCache (int maxSize) {// specify the number of cached data. if (maxSize <= 0) {// It must be greater than 0 throw new IllegalArgumentException (maxSize <= 0);} this. maxSize = maxSize; this. map = new LinkedHashMap
 
  
(0, 0.75f, true); // create a LinkedHashMap and sort it by the order of accessed Data}
 
(2)As you can see from the preceding constructor, you must specify the number of cached data when creating an LruCache. here we need to explain in detail what the number of cached data actually refers to: the number of cached data objects, or the total memory occupied by cached data?

 

The answer is: yes. it can be the number of cached data, or the total memory occupied by the cached data. It can also be other data. what is it? It depends on how your LruCache rewrite this method: sizeOf (K key, V value)

 

Protected int sizeOf (K key, V value) {// subclass overwrite this method to calculate the amount occupied by each stored data in your cache. return 1; // 1 is returned by default. This indicates that the number of cached data is the total number of cached data by default (each data is 1 ).}
So if I use LruCache to save bitmap images and want the cache capacity to be 4 MB, what should I do? In the original description, android provides an example:

 

 

 * 

By default, the cache size is measured in the number of entries. override * {@ link # sizeOf} to size the cache in different units. for example, this cache * is limited to 4MiB of bitmaps :*

{@ Code * int cacheSize = 4*1024*1024; // 4MiB * LruCache
 
  
BitmapCache = new LruCache
  
   
(CacheSize) {// Save the LruCache of bitmap. The capacity is 4 M * protected int sizeOf (String key, Bitmap value) {* return value. getByteCount (); // calculate the memory size occupied by each cached image *}*}}
  
 
(3)How does LruCache determine whether the cache is full and how to remove infrequently used data?

 

In fact, there is a method in LruCache: trimToSize () is used to check whether the current time is full. If it is full, a data is automatically removed until it is not satisfied:

 

Public void trimToSize (int maxSize) {// by default, this is the maximum capacity value mentioned above. maxSize while (true) {// infinite loop. ensure that K key; V value; synchronized (this) {// thread security guarantee if (size <0 | (map. isEmpty () & size! = 0) {throw new IllegalStateException (getClass (). getName () +. sizeOf () is reporting inconsistent results !); } If (size <= maxSize) {// if not, the loop break will jump out;} Map. Entry
 
  
ToEvict = map. eldest (); // retrieve the final data (least commonly used data) if (toEvict = null) {break;} key = toEvict. getKey (); value = toEvict. getValue (); map. remove (key); // remove this data size-= safeSizeOf (key, value); // capacity reduction evictionCount ++; // update the number of automatically removed data (times )} entryRemoved (true, key, value, null); // It is used to notify the data to be removed. If you need to know when a data is removed, you need to write this method entryRemoved }}
 
I have provided a description in the source code above, which is easy to understand. note that the trimToSize method is public, indicating that we can call this method by ourselves. this is important. remember him, you will use it.

 

The following question is: when will trimToSize be called?

TrimToSize this method is called in multiple methods in LruCache to check whether it is full. For example, you can add a new data method to LruCache in put, trimToSize is also called to detect a data obtained through the get (K key) method. next let's take a look at how to call put:

 

Public final V put (K key, V value) {// Add a new data if (key = null | value = null) {throw new NullPointerException (key = null | value = null);} V previous; synchronized (this) {putCount ++; size + = safeSizeOf (key, value ); previous = map. put (key, value); if (previous! = Null) {size-= safeSizeOf (key, previous) ;}} if (previous! = Null) {// remove old data entryRemoved (false, key, previous, value);} trimToSize (maxSize ); // check whether the cached data is full. return previous ;}

(4)After reading the source code above, we can find that synchronized was added to all operations on LruCache to ensure thread security. Yes, LruCache is thread-safe, other methods are also used for synchronized.

 

(5)In fact, you should immediately have a question: What if the LruCache has deleted a data, but now it calls the LruCache get method to obtain the data? Let's see if the source code solves this problem:

 

Public final V get (K key) {// obtain a data if (key = null) {throw new NullPointerException (key = null);} V mapValue; synchronized (this) {mapValue = map. get (key); if (mapValue! = Null) {// obtain the data hitCount ++; // return mapValue when the data is obtained; // The data is obtained successfully} missCount ++; // number of failed data retrieval}/** Attempt to create a value. this may take a long time, and the map * may be different when create () returns. if a conflicting value was * added to the map while create () was working, we leave that value in * the map and release the created value. */V createdValue = create (key); // try to create this data if (createdVa Lue = null) {return null; // data creation failed} synchronized (this) {// Add the re-created data createCount ++; // Number of new data creation times mapValue = map. put (key, createdValue); if (mapValue! = Null) {// There was a conflict so undo that last put map. put (key, mapValue);} else {size + = safeSizeOf (key, createdValue);} if (mapValue! = Null) {entryRemoved (false, key, createdValue, mapValue); return mapValue;} else {trimToSize (maxSize); // check whether return createdValue is full ;}}
From the above analysis, we can re-create nonexistent data from the create method. This method does nothing by default, so you need to do it yourself.

 

 

    protected V create(K key) {        return null;    }

 

 

 

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.