Android Open source Framework Universal-image-loader learn three--usingfreqlimitedmemorycache source reading

Source: Internet
Author: User



Universal-image-loader's Memory cache policy

1. Use only strong reference caching

    • Lrumemorycache (This class is the default memory cache class for the open source framework, which caches the strong references of bitmap)

2. A cache with strong references and weak references

    • usingfreqlimitedmemorycache (if the total number of cached pictures exceeds the limit, first delete the bitmap with the least frequency)
    • Lrulimitedmemorycache (which is also used by the LRU algorithm, unlike Lrumemorycache, which he caches is a weak reference to bitmap)
    • fifolimitedmemorycache (FIFO caching policy, When the set value is exceeded, first delete the bitmap that was first added to the cache)
    • largestlimitedmemorycache (delete the largest bitmap object first when exceeding the cache limit)
    • Limitedagememorycache (Delete the bitmap when it has been added to the cache for more than the value we set)

3. Use only weak reference caching

    • Weakmemorycache (there is no limit to the total size of this type of cache bitmap, the only thing that is not stable, cached images are easily recycled)


Inheritance Relationship:

public class Usingfreqlimitedmemorycache extends Limitedmemorycachepublic abstract class Limitedmemorycache extends Basememorycachepublic Abstract class Basememorycache implements Memorycachepublic interface MemoryCache extends memorycacheaware<string, bitmap> @Deprecatedpublic interface memorycacheaware<k, v>

1. First Look Memorycacheaware:


/* Interface for memory cache*/@Deprecatedpublic Interface memorycacheaware<k, v> {    /*puts value to cache by K EY     * @return true-if value is put into cache successfully;false-if value is not put into cache     */    Boolea N Put (K key, V value);     /** Returns value by key. If there is no value for key then NULL would be returned. *    /V Get (K key);     /** removes item by key *    /V Remove (K key);     /** Returns All keys of the cache *    /collection<k> keys ();     /** Remove all items from cache *    /void clear ();

2, now generally use memorycache replace memorycacheaware:

Memorycacheaware Source:

Public interface MemoryCache extends Memorycacheaware<string, bitmap> {}

3. basememorycache Source:

/* provides some basic functionality for memory cache; Provides a reference to object (non-strong reference) storage */public abstract class Basememorycache implements MemoryCache {/** storage objec Non-strong references to TS, COLLECTIONS.SYNCHRONIZEDMAP guaranteed thread safety */private final map<string, reference<bitmap>> softmap =     Collections.synchronizedmap (New hashmap<string, reference<bitmap>> ());        @Override public Bitmap get (String key) {Bitmap result = null;        reference<bitmap> Reference = Softmap.get (key);        if (reference! = null) {result = Reference.get ();    } return result;        } @Override public Boolean put (String key, Bitmap value) {softmap.put (Key, Createreference (value));    return true;        } @Override Public Bitmap remove (String key) {reference<bitmap> bmpref = Softmap.remove (key); return bmpref = = null?    Null:bmpRef.get (); } @Override public collection<string> keys () {synchronized (Softmap) {return new hashset& Lt String> (Softmap.keyset ());    }} @Override public void Clear () {softmap.clear (); }/** creates {@linkplain Reference not strong} Reference of value */protected abstract reference<bitmap> CR  Eatereference (Bitmap value);}

4. Limitedmemorycache Source:

/** * Limited cache. provides storage for object. The total memory size of all stored bitmap does not exceed the limit value * Note: The cache uses strong references and weak references to store bitmaps; * Strong citation-for bitmaps * Weak application within limits-for other bitmaps */public abstract class Limitedmemorycache extends Basememorycache {private    static final int max_normal_cache_size_in_mb = 16;     private static final int max_normal_cache_size = MAX_NORMAL_CACHE_SIZE_IN_MB * 1024 * 1024;    private final int sizeLimit;     /*atomicinteger, an integer class that provides atomic manipulation, makes the operation thread safe */private final Atomicinteger cacheSize; /** * contains strong references to storage objects.         Each object is added to the tail end, and if the hard cache exceeds the limit, the object on the first end will be deleted * (but it still exists in softmap and can be collected at any time by GC)//Returns a thread-safe list of synchronizes packages public static <T> list<t> synchronizedlist (list<t> List) */private final list<bitmap> H     Ardcache = collections.synchronizedlist (New linkedlist<bitmap> ());        /** constructor: SizeLimit Unit bytes */public limitedmemorycache (int sizeLimit) {this.sizelimit = SizeLimit;        CacheSize = new Atomicinteger (); /** detection avoids SizeLimit value settingToo large */if (SizeLimit > Max_normal_cache_size) {L.W ("You set too large memory CACHE SIZE", more than%1        $d Mb) ", MAX_NORMAL_CACHE_SIZE_IN_MB); }} The/** operation returned true successfully, the operation failed to return false first attempt to add bitmap to hard cache, and then add it to soft cache*/@Override public boolean put (S                Tring key, Bitmap value) {Boolean putsuccessfully = false;    int valuesize = GetSize (value);    Abstract function that returns the size value of bitmap int sizeLimit = Getsizelimit (); returns sizelimit int curcachesize = Cachesize.get ();//Returns the current value of cacheSize/** if the added bitmap size is greater than sizelimit, it is not added directly to the Hard cache*/if (Valuesize < SizeLimit) {/** determines the valuesize of the newly added object plus the curcachesize of the object already in the current cache exceeds the limit Value, the appropriate bitmap*/while (Curcachesize + valuesize > SizeLimit) {Bitmap Removedvalue = Remove    Next (); The abstract function, which returns the next bitmap if (Hardcache.remove (Removedvalue)) {curcachesize = cache) that needs to be deleted Size.addandget (-getsize (RemovedvAlue));          }} hardcache.add (value); Add to Linkedlist<bitmap> tail cachesize.addandget (valuesize);//Cachesize+valuesize PUTSUC        Cessfully = true;        }//ADD value to soft cache super.put (key, value);    return putsuccessfully;        } @Override Public Bitmap remove (String key) {Bitmap value = Super.get (key);            if (value! = null) {if (Hardcache.remove (value)) {Cachesize.addandget (-getsize (value));    }} return Super.remove (key);        } @Override publicvoid Clear () {hardcache.clear ();        Cachesize.set (0);    Super.clear ();    } protected int Getsizelimit () {return sizeLimit;     } protected abstract int getsize (Bitmap value);  Protected abstract Bitmap Removenext ();}

5. usingfreqlimitedmemorycache Source: (The key is the update usage frequency in Get)

/** * Limited {@link Bitmap Bitmap} cache. Provides {@link Bitmap bitmaps} storing. Size of all stored bitmaps won't to * exceed size limit. When cache reaches limit size then the bitmap which used the least frequently are deleted from * cache (remove minimum frequency of bitmap) * N OTE: Using strong references and weak references; * Strong reference: for limited count of Bitmaps (depends on cache size) * Weak application: For all other cached Bitmaps */public clas S Usingfreqlimitedmemorycache extends Limitedmemorycache {/** * Contains strong references to stored objects (keys ) and last object, usage date (in milliseconds). If Hard Cache * Size would exceed limit then object with the least frequently usage was deleted (but it continue exist a T * {@link #softMap} and can be collected by GC at any time) */private final map<bitmap, integer> USINGC     Ounts = Collections.synchronizedmap (New Hashmap<bitmap, integer> ());    Public Usingfreqlimitedmemorycache (int sizeLimit) {super (sizeLimit); } @Override public Boolean put (STring key, Bitmap value) {if (Super.put (key, value)) {usingcounts.put (value, 0);        return true;        } else {return false;        }} @Override public Bitmap get (String key) {Bitmap value = Super.get (key);        If value exists, then usagecount+ 1;            if (value = null) {Integer Usagecount = usingcounts.get (value);            if (usagecount! = null) {//Update value corresponds to the Usagecount values Usingcounts.put (value, Usagecount + 1);    }} return value;        } @Override Public Bitmap remove (String key) {Bitmap value = Super.get (key);        if (value = null) {Usingcounts.remove (value);    } return Super.remove (key);        } @Override public void Clear () {usingcounts.clear ();    Super.clear ();    } @Override protected int getsize (Bitmap value) {return value.getrowbytes () * Value.getheight (); } @Override Protected Bitmap Removenext () {Integer minusagecount = null;        Bitmap leastusedvalue = null;        Set<entry<bitmap, integer>> entries = Usingcounts.entryset (); Synchronized (usingcounts) {for (Entry<bitmap, integer> entry:entries) {//Initialize LEASTUSEDV                    Alue if (Leastusedvalue = = null) {Leastusedvalue = Entry.getkey ();                Minusagecount = Entry.getvalue ();                    } else {//simple comparison gets the minimum value of Integer lastvalueusage = Entry.getvalue ();                        if (Lastvalueusage < minusagecount) {minusagecount = Lastvalueusage;                    Leastusedvalue = Entry.getkey ();        }}}} usingcounts.remove (Leastusedvalue);    return leastusedvalue; } @Override protected reference<bitmap> createreference (Bitmap value) {return new WeakrefeRence<bitmap> (value); }}






Android Open source Framework Universal-image-loader learn three--usingfreqlimitedmemorycache source reading

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.