Android LruCache類分析

來源:互聯網
上載者:User

標籤:建立   report   儲存   linked   epo   trim   oev   form   creat   

public class LurCache<K, V> {    private final LinkedHashMap<K, V> map;    private int size; // 已經儲存的大小    private int maxSize; // 規定的最大儲存空間    private int putCount; // put的次數    private int createCount; // create的次數    private int evictionCount; // 回收的次數    private int hitCount; // 命中的次數    private int missCount; // 丟失的次數    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);    }    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++; // 命中                return mapValue;            }            missCount++; // 丟失        }        V createdValue = create(key);        if (createdValue == null) {            return null;        }        synchronized (this) {            createCount++;// 建立++            mapValue = map.put(key, createdValue);            if (mapValue != null) {                // There was a conflict so undo that last put                // 如果前面存在oldValue,那麼撤銷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;        }    }        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) {  //返回的先前的value值                size -= safeSizeOf(key, previous);              }          }            if (previous != null) {              entryRemoved(false, key, previous, value);          }            trimToSize(maxSize);          return previous;      }      //清空cache空間    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 results!");                  }                    if (size <= maxSize) {                      break;                  }                    Map.Entry<K, V> toEvict = map.entrySet().iterator().next();                  if (toEvict == null) {                      break;                  }                    key = toEvict.getKey();                  value = toEvict.getValue();                  map.remove(key);                  size -= safeSizeOf(key, value);                  evictionCount++;              }                entryRemoved(true, key, value, null);          }      }      //刪除key相應的cache項,返回相應的value    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;      }      //當item被回收或者刪掉時調用。該方法當value被回收釋放儲存空間時被remove調用, 或者替換item值時put調用,預設實現什麼都沒做。    //true: 為釋放空間被刪除;false: put或remove導致    protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}         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;      }          protected int sizeOf(K key, V value) {          return 1;      }    //清空cache    public final void evictAll() {          trimToSize(-1); // -1 will evict 0-sized elements      }        public synchronized final int size() {          return size;      }        public synchronized final int maxSize() {          return maxSize;      }        public synchronized final int hitCount() {          return hitCount;      }        public synchronized final int missCount() {          return missCount;      }        public synchronized final int createCount() {          return createCount;      }        public synchronized final int putCount() {          return putCount;      }        //返回被回收的數量    public synchronized final int evictionCount() {          return evictionCount;      }      //返回當前cache的副本,從最近最少訪問到最多訪問    public synchronized final Map<K, V> snapshot() {          return new LinkedHashMap<K, V>(map);      }        public synchronized final String toString() {          int accesses = hitCount + missCount;          int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;          return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",                  maxSize, hitCount, missCount, hitPercent);      }  }

 

Android LruCache類分析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.