Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

LruCache 完全解析:記憶體快取原理、源碼剖析與圖片快取實例

編輯:關於 Android 程式設計

圖片快取做不做,直接決定了列表捲動是順滑還是卡頓。而談到 Android 上的記憶體快取,LruCache 幾乎是標準答案。

為什麼要在記憶體中做快取

記憶體快取能讓重複出現的圖片不必重新解碼,省下的是最寶貴的時間。但它會佔用應用程式的記憶體空間,因此需要一個「有上限、會自動淘汰」的容器——這正是 LruCache 的定位。它透過支援包可相容到 API 4,內部以 LinkedHashMap 保持強引用,當快取超過設定值時,自動釋放最早存進來的資料。

順帶一提,早期常見的做法是用 SoftReference 或 WeakReference 實作快取,但現在並不建議。從 Android 2.3(API 9)開始,垃圾回收器變得更積極地回收軟/弱引用,讓這類快取近乎失效;而在 Android 3.0(API 11)之前,位於 native 記憶體中的 Bitmap 不會被隨物件一起釋放,容易造成應用暫時超出記憶體上限而崩潰。

什麼是 LRU

LRU 是 Least Recently Used 的縮寫,中文叫「最近最少使用」。它的規則很樸素:快取固定容量,當資料總量超過閾值時,淘汰最久沒被使用的那一份。

舉例說,我們規定快取上限 100MB。總量低於 100MB 時隨意添加;一旦超過,就必須先丟掉最舊的資料,再放新的進來,讓總量穩定維持在 100MB 以內。關鍵問題是「誰最舊」——這就交給 LRU 的排序策略來回答。

源碼剖析

LruCache 位於 android.support.v4 套件中,實作基礎是 LinkedHashMap。選用 LinkedHashMap 有兩個好處:一是它可以配置成「依存取順序排序」,最近讀取的排在前面、最久未讀的落在後面;二是它提供了 removeEldestEntry() 這個鉤子,讓我們在資料量超標時移除最舊的一項。

Android 源碼選擇的是委派(delegation)而非繼承,寫法相當乾淨:

public class LruCache {
    private final LinkedHashMap map;
    private int size;          // 目前已快取的大小
    private int maxSize;       // 設定的上限
    private int putCount;
    private int createCount;
    private int evictionCount; // 被淘汰的次數
    private int hitCount;      // 命中次數
    private int missCount;     // 未命中次數

    public LruCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        // 第三個參數 true 是關鍵:改為依存取順序排序
        this.map = new LinkedHashMap(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) {
                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();
        V previous;
        synchronized (this) {
            putCount++;
            size += safeSizeOf(key, value);
            previous = map.put(key, value);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }
        trimToSize(maxSize);
        return previous;
    }

    public 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 || map.isEmpty()) {
                    break;
                }
                Map.Entry toEvict = map.entrySet().iterator().next();
                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                size -= safeSizeOf(key, value);
                evictionCount++;
            }
            entryRemoved(true, key, value, null);
        }
    }
}

有兩個方法需要子類覆寫,否則 LruCache 只是個普通容器:

sizeOf(K key, V value):回報每個項目的「大小」。預設回傳 1,也就是以「個數」計算;若要依記憶體計算,就必須覆寫它,例如回傳 bitmap.getByteCount()。這個方法決定了 maxSize 的單位,兩者必須呼應——maxSize 填的是 5MB,sizeOf 卻回傳 1,淘汰邏輯就會完全失效。

entryRemoved(boolean evicted, K key, V oldValue, V newValue):項目被移除時的回呼。evicted 為 true 代表為了騰空間而被淘汰,false 則是被 put 或 remove 主動替換。在這裡我們可以完成真正的記憶體釋放。

此外還有一批唯讀的統計方法:hitCount()、missCount()、createCount()、putCount()、evictionCount(),以及 toString() 會輸出命中率。上線後看這些數字,比憑感覺調參有用得多。

實例:以 LruCache 快取 Bitmap

繼承 LruCache,實作 sizeOf 與 entryRemoved:

public class BitmapCache extends LruCache {
    private BitmapRemovedCallBack mRemovedCallBack;

    public BitmapCache(int maxSize, BitmapRemovedCallBack callBack) {
        super(maxSize);
        mRemovedCallBack = callBack;
    }

    @Override protected int sizeOf(K key, V value) {
        return value == null ? 0 : value.getByteCount();
    }

    @Override protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {
        super.entryRemoved(evicted, key, oldValue, newValue);
        if (evicted && oldValue != null) {
            // 回收前務必先解除 View 對 Bitmap 的引用,
            // 否則極易出現 "Canvas: trying to use a recycled bitmap"
            mRemovedCallBack.onBitmapRemoved(key);
            oldValue.recycle();
        }
    }

    public interface BitmapRemovedCallBack {
        void onBitmapRemoved(K key);
    }
}

使用時,快取大小建議取「單一應用可用記憶體的八分之一」,用記憶體單位而非個數:

private BitmapCache mMemoryCache;

private BitmapCache.BitmapRemovedCallBack mRemovedCallBack =
        new BitmapCache.BitmapRemovedCallBack() {
    @Override public void onBitmapRemoved(String key) {
        // 在這裡把相關 ImageView 的 Bitmap 設為 null
    }
};

@Override protected void onCreate(Bundle savedInstanceState) {
    int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
    int cacheSize = 1024 * 1024 * memClass / 8;
    mMemoryCache = new BitmapCache(cacheSize, mRemovedCallBack);
}

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

載入圖片時,先查快取,命中就立刻更新 ImageView,未命中則顯示佔位圖並啟動背景任務:

public void loadBitmap(int resId, ImageView imageView) {
    final String imageKey = String.valueOf(resId);
    final Bitmap bitmap = getBitmapFromMemCache(imageKey);
    if (bitmap != null) {
        imageView.setImageBitmap(bitmap);
    } else {
        imageView.setImageResource(R.drawable.image_placeholder);
        new BitmapLoadingTask(imageView).execute(resId);
    }
}

class BitmapLoadingTask extends AsyncTask {
    @Override protected Bitmap doInBackground(Integer... params) {
        Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), params[0], 100, 100);
        addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
        return bitmap;
    }
}

重點回顧

一、LruCache 是基於 LRU 演算法的快取容器,淘汰策略是「最近最少使用」。

二、觸發淘汰的前提是當前總量超過設定上限,上限的單位由 sizeOf() 決定。

三、LruCache 本身不釋放記憶體,它只是把物件從 Map 中移除;Bitmap 這類佔用 native 記憶體的物件,仍需你手動 recycle()。

四、recycle 之前,一定要先解除 View 對該 Bitmap 的引用,否則繪製時會直接拋出例外。

如果還需要跨啟動存活的大圖快取,可以搭配 DiskLruCache(JakeWharton 的開源實作)做磁碟層快取,形成記憶體加磁碟的雙層結構,這也是主流圖片框架的基本骨架。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved