LruCache原理

LruCache 裏面最要有幾個重要因素

  • 設置LruCache緩存的大小,一般爲當前進程可用容量的1/8
  • 重寫sizeOf方法,計算出要緩存的每張圖片的大小
int maxMemory = (int) (Runtime.getRuntime().totalMemory()/1024);
        int cacheSize = maxMemory/8;
        mMemoryCache = new LruCache<String,Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes()*value.getHeight()/1024;
            }
        };
  • 最近最少使用算法
  • 最近最少使用算法的實現是通過LinkedHashMap來實現的,沒有軟引用,都是強引用
  • 如果添加的數據大於設置的最大值,就刪除最先緩存的數據來調整內存。他的主要原理在trimToSize方法中
LinkedHashMap
  • LinkedHashMap繼承於HashMap,它使用了一個雙向鏈表來存儲Map中的Entry順序關係,
  • 這種順序有兩種,一種是LRU順序,一種是插入順序,可通過構造方法設置
  • LRU順序(訪問順序:表示雙向鏈表中的元素按照訪問的先後順序排列):get時將該對象移到鏈表的尾部,put插入新的對象也是存儲在鏈表的尾部,這樣當內存緩存達到設定的最大值時,將鏈表頭部的對象(最近最少用到的)移除,
  • 插入順序:是按照插入的順序實現的,put時插入新的對象是存儲在鏈表的尾部,就是當標誌位accessOrder的值爲false時
設置LinkedHashMap的存儲順序

通過構造方法進行指定

public LinkedHashMap(int initialCapacity,
                         float loadFactor,
                         boolean accessOrder) {
        super(initialCapacity, loadFactor);
        this.accessOrder = accessOrder;
    }

其中accessOrder設置爲true則爲訪問順序,爲false,則爲插入順序

例子:當設置爲true時

public static final void main(String[] args) {
        LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>(0, 0.75f, true);
        map.put(0, 0);
        map.put(1, 1);
        map.put(2, 2);
        map.put(3, 3);
        map.put(4, 4);
        map.put(5, 5);
        map.put(6, 6);
        map.get(1);
        map.get(2);

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());

        }
    }

輸出結果:

0:0
3:3
4:4
5:5
6:6
1:1
2:2

這就最近最少使用算法的順序(訪問順序)

LruCache是用作緩存,既然涉及到了緩存必定有put、get 方法,接下來就看下LruCache 中的put和get方法

LruCache中的put方法:
public final V put(K key, V value) {
         //不可爲空,否則拋出異常
        if (key == null || value == null) {
            throw new NullPointerException("key == null || value == null");
        }
        V previous;
        synchronized (this) {
            //插入的緩存對象值加1
            putCount++;
            //增加已有緩存的大小
            size += safeSizeOf(key, value);
           //向map中加入緩存對象
            previous = map.put(key, value);
            //如果已有緩存對象,則緩存大小恢復到之前
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
        //entryRemoved()是個空方法,可以自行實現
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }
        //調整緩存大小(關鍵方法)
        trimToSize(maxSize);
        return previous;
    }

關鍵點是在調用了put方法中還執行了trimToSize()方法,作用是判斷緩存大小是否夠用,如果不夠需要先刪除近期少訪問的元素

看下trimToSize()方法

 public void trimToSize(int maxSize) {
        while (true) {
            K key;
            V value;
            synchronized (this) {
            //如果map爲空並且緩存size不等於0或者緩存size小於0,拋出異常
                if (size < 0 || (map.isEmpty() && size != 0)) {
                    throw new IllegalStateException(getClass().getName()
                            + ".sizeOf() is reporting inconsistent results!");
                }

                //如果緩存大小size小於最大緩存,不需要再刪除緩存對象,跳出循環
                if (size <= maxSize) {
                    break;
                }
                //獲取head,近期最少訪問的元素
                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);
        }
    }
LruCache 中的 get() 方法
public final V get(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        V mapValue;
        synchronized (this) {
            //獲取對應的緩存對象
            //LinkedHashMap 的 get()方法會實現將訪問的元素更新到隊列尾部的功能
            mapValue = map.get(key);
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount++;
                return mapValue;
            }
            missCount++;
        }
        //省略
    }

進入LinkedHashMap的get()方法

public V get(Object key) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) == null)
            return null;
        if (accessOrder)//如果是訪問順序
            //將訪問的元素移到隊列的尾部
            afterNodeAccess(e);
        return e.value;
    }

再深入瞭解可以看下LinkedHashMap的原理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章