The Lrucache_java of Java resource caching

Source: Internet
Author: User

For example, to cache a picture for a network load:

  Gets the largest memory
    int maxmemory= (int) runtime.getruntime () that the application is allocated (). MaxMemory ();
    1/5 of the memory used when the cache size
    int cachsize=maxmemory/5;
    Instantiate LruCache
    lrucache=new lrucache<string, bitmap> (cachsize) {
      //internal method sizeof set the cache size
      for each picture  protected int sizeOf (String key, Bitmap value) {
        //is called each time the cache is cached, telling the system how large the cached picture is
        //is equivalent to allocating the size space for each resource to be cached.
        Value.getbytecount ();
      }
    ;
     

The code above is usually in the initialization method.

You can actually interpret the Lurcache class as a map class map with put and get methods

Next, call the put and get methods to access the cached resources.

Lurcache's Add:

public void Putbitmaptocache (String url,bitmap Bitmap) {
    if (getbitmapfromcache (URL) ==null) {//To determine whether the current cache exists
      Lrucache.put (URL, bitmap);
    }
Lurcache get: Public

Bitmap getbitmapfromcache (String url) {
    return lrucache.get (URL);//You can treat LruCache as a map
  }

It is easy to call the add and get methods above to cache resources.

But be aware that one point LruCache lruCache=new LruCache<String, Bitmap>(cachSize) can only be new once, otherwise different objects will be different cache

Attach the Android LRUCache class

Package android.util; 
Import Java.util.LinkedHashMap; 
 
Import Java.util.Map; /** * A cache that holds strong references to a limited number of values. Each time * A value was accessed, it is moved to the head of a queue. When a value was * added to a full cache, the value at the "end of" \ Evicted and may * become eligible for G 
 Arbage collection.
 * Cache saves a strong reference to limit the amount of content, and whenever item is accessed, the item is moved to the head of the queue.
 * When a new item is added when the cache is full, the item at the end of the queue is reclaimed. 
 * <p>if your cached values hold resources this need to be explicitly released, * override {@link #entryRemoved}. * If a value of your cache needs to be explicitly released, rewrite entryremoved () * <p>if a cache miss should be computed to demand for the corresponding key S, * override {@link #create}. This is simplifies the calling code, allowing it to * assume a value would always be returned, even when there ' s a cache mis
 S. * If the corresponding item of key is lost, rewrite create (). This simplifies the calling code and always returns even if it is lost. * <p>by default, the cache size is measured in the number of entries. OvErride * {@link #sizeOf} to size of the cache in different units.
 For example, this cache * was limited to 4MiB of bitmaps: The default cache size is the number of item measurements, and the rewrite sizeof calculates the size of the different item. * <pre> {@code * int cacheSize = 4 * 1024 * 1024;//4MiB * lrucache<string, bitmap> bitmapcache = new Lrucache<string, bitmap> (cacheSize) {* protected int sizeOf (String key, Bitmap value) {* return value. 
 GetByteCount (); *}}</pre> * * <p>this class is thread-safe. Perform multiple cache operations atomically by * Synchronizing on the cache: <pre> {@code * synchronized (CAC 
 He) {* if (cache.get (key) = null) {* CACHE.PUT (key, value); *}}</pre> * * <p>this class does not allow NULL to be used as a key or value. A return * value of NULL from {@link #get}, {@link #put} or {@link #remove} is * unambiguous:the key
 Ache. * Do not allow key or value NULL * when get (), put (), remove () return value is NULL, key corresponding item is not a CAChe in the public class lrucache<k, v> {private final linkedhashmap<k, v> map; /** Size of this cache in units. Not necessarily the number of elements. * * private int size; Already stored size private int maxSize; The specified maximum storage space is private int putcount; Put the number of times private int createcount; Create the number of times private int evictioncount; Number of recycled private int hitcount; Number of hits private int misscount; Number of Lost/** * @param maxSize for caches that does not override {@link #sizeOf}, this is * the maximum numbers o F entries in the cache. 
   For all other caches, * it is the maximum sum of the sizes of the the entries in this cache. */public LruCache (int maxSize) {if (maxSize <= 0) {throw new IllegalArgumentException ("MaxSize <= 
    0 "); 
    } this.maxsize = MaxSize; 
  This.map = new linkedhashmap<k, v> (0, 0.75f, true); }/** * Returns the value for {@code key} if it exists in the cache or can is * created by {@code #creATE}. If A value was returned, it's moved to the "*" Head of the queue. This returns null if a value isn't cached and cannot * is created. Return the item by key, or create a return item.
   The item is moved to the head of the queue, * returns NULL if the value of item is not cache or cannot be created. 
    * * Public final V get (K key) {if (key = = null) {throw new NullPointerException ("key = = null"); 
    } V Mapvalue; 
      Synchronized (this) {Mapvalue = Map.get (key); 
      if (mapvalue!= null) {hitcount++;//Hit return mapvalue; } misscount++; Lost}/* * Attempt to create a value. This could take a long, and the map * may different when create () returns.  If a conflicting value is * added to "map while create () is working, we leave that value in * the map and 
     Release the created value. 
    * If lost, try to create an item */V Createdvalue = Create (key); 
    if (Createdvalue = = null) {return null; 
} synchronized (this) {      createcount++;//Create + + Mapvalue = map.put (key, Createdvalue); 
        if (mapvalue!= null) {//There is a conflict so undo, then put//If the front exists oldvalue, then undo put () 
      Map.put (key, Mapvalue); 
      else {size = safesizeof (key, Createdvalue); 
      } if (Mapvalue!= null) {entryremoved (False, Key, Createdvalue, Mapvalue); 
    return mapvalue; 
      else {trimtosize (maxSize); 
    return createdvalue; }/** * Caches {@code value} for {@code key}. 
   The value is moved to the head of the queue. 
   * * @return The previous value mapped by {@code key}. * Public final V put (K key, V value) {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) {//returns the previous value value of size = safesizeof (key, previous); 
    } if (previous!= null) {entryremoved (False, key, previous, value); 
    } trimtosize (MaxSize); 
  return previous; }/** * @param maxSize The maximum size of the cache before returning. 
   May be-1 * To evict even 0-sized elements. 
      * Empty Cache space */private void trimtosize (int maxSize) {while (true) {K key; 
      V value; Synchronized (this) {if (Size < 0 | | (Map.isempty () && size!= 0)) {throw new IllegalStateException (GetClass (). GetName () + ". SizeOf () is reporting inconsistent re 
 
        Sults! ");} 
        if (size <= maxSize) {break; 
        } map.entry<k, v> toevict = Map.eldest (); 
        if (toevict = = null) {break; 
        Key = Toevict.getkey (); 
        Value = Toevict.getvalue (); 
        Map.Remove (key); SiZe-= safesizeof (key, value); 
      evictioncount++; 
    } entryremoved (True, key, value, NULL); 
   }/** * Removes the entry for {@code key} if it exists. 
   * Delete key corresponding cache entry, return the corresponding value * @return The previous value mapped by {@code key}. 
    * * Public final V remove (K key) {if (key = = null) {throw new NullPointerException ("key = = null"); 
    } V Previous; 
      Synchronized (this) {previous = Map.Remove (key); 
      if (previous!= null) {size = Safesizeof (key, previous); 
    } if (previous!= null) {entryremoved (False, key, previous, NULL); 
  return previous; /** * called for entries that have been evicted or removed. This is * invoked when a value is evicted to make spaces, removed by a call to * {@link #remove}, or replace D by a call to {@link #put}. 
   The default * implementation does nothing. * Called when item is recycled or deleted. The modified method is REM when value is reclaimed to release storage spaceOve calls, * or replaces the item value with the put call, the default implementation does nothing. * <p>the method are called without synchronization:other threads may * access the cache while this is EXE 
   Cuting. * * @param evicted True if the entry is being removed to make spaces, false * if the removal was caused by a {@li 
   NK #put} or {@link #remove}. * True---to free space is deleted; false---Put or remove causes * @param newvalue The new value for {@code key}, if it exists. If Non-null, * This removal is caused by a {@link #put}. 
   Otherwise it is caused by * a eviction or a {@link #remove}. * * protected void entryremoved (Boolean evicted, K key, v OldValue, v newvalue) {}/** * called after a cache m 
   ISS to compute a value for the corresponding key. * Returns the computed value or null if no value can be computed. 
   The * default implementation returns NULL. * When an item is lost, it is called to return the corresponding value of the calculation or NULL * <p>the method is called without synchronization:other threads may * AC Cess the CACIt is executing. * * <p>if a value for {@code key} exists in the cache as this method * returns, the created value would be Released with {@link #entryRemoved} * and discarded. This can occur when multiple threads request the same key * at the same time (causing multiple values to be created), 
   or when one * thread calls {@link #put} while another be creating a value for the same * key. 
  * * Protected V Create (K key) {return null; 
    private int safesizeof (K key, V value) {int result = SizeOf (key, value); 
    if (Result < 0) {throw new IllegalStateException ("Negative size:" + key + "=" + value); 
  return result; }/** * Returns the size of the entry for {@code key} and {@code value} in * user-defined units. The default implementation returns 1 so this size * is the number of entries and max size is the maximum number of ENT 
   Ries. * Return the size of the user-defined item, the default return of 1 represents the number of item, the largest SIZe is the maximum item value * <p>an entry ' s size must not a while it's in the cache. 
  * * Protected int sizeOf (K key, V value) {return 1; 
   /** * Clear the cache, calling {@link #entryRemoved} on each removed entry. 
   * Empty Cacke/public final void Evictall () {trimtosize ( -1);//-1 would evict 0-sized elements}/** * For caches that does not override {@link #sizeOf}, this returns the number * of entries in the cache. 
   For all other caches, this is returns the sum of * The sizes of the entries in this cache. 
  * * Public synchronized final int size () {return size; /** * For caches that does not override {@link #sizeOf}, this returns the maximum * number of entries in the Cache. 
   For all other caches, this is returns the * maximum sum of the sizes of the entries in this cache. 
  * * Public synchronized final int maxSize () {return maxSize; }/** * Returns the number of times {@link #get} retuRned a value that is * already present in the cache. 
  * * Public synchronized final int Hitcount () {return hitcount; 
   /** * Returns the number of times {@link #get} returned null or required a new * value to be created. 
  * * Public synchronized final int Misscount () {return misscount; 
   /** * Returns the number of times {@link #create (Object)} returned a value. 
  * * Public synchronized final int Createcount () {return createcount; 
   /** * Returns the number of times {@link #put} is called. 
  * * Public synchronized final int Putcount () {return putcount; 
   }/** * Returns the number of values that have been evicted. 
  * Returns the number of recycled * * Public synchronized final int Evictioncount () {return evictioncount; }/** * Returns a copy of the current contents of the cache, ordered from least * recently accessed to most R ecently accessed. Returns a copy of the current cache, from the least recent access to the maximum access/pUblic synchronized final map<k, v> snapshot () {return new linkedhashmap<k, v> (MAP); 
    @Override public Synchronized Final String toString () {int accesses = Hitcount + Misscount; int hitpercent = accesses!= 0? 
    (MB * hitcount/accesses): 0; Return String.Format ("lrucache[maxsize=%d,hits=%d,misses=%d,hitrate=%d%%]", MaxSize, Hitcount, Misscount, HitPerc 
  ENT); } 
}

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.