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

從源碼看 Universal Image Loader 的緩存機制設計

編輯:關於 Android 程式設計

UIL 是國內外都很熱門的圖片載入庫。讀過它的緩存實作後會發現,其實沒有什麼高深的技巧——沒有複雜的進程調度,也沒有層層的異常防護,程式碼寫得相當直白。但正因為它被這麼多人使用,把它的實作搞懂就很有價值。本文先看整體流程,再逐段拆 LruMemoryCache 與 BaseDiscCache。

整體緩存流程

參與者只有三個:UI、緩存模組、資料來源(網路)。流程如下:

  1. UI 以唯一的 key 向記憶體緩存索取 Bitmap。
  2. 記憶體緩存比對 key,命中就直接回傳;未命中進入下一步。
  3. 以同一個 key 對應的檔名,去 SD 卡上找檔案。
  4. 找到就用 BitmapFactory.decode* 解碼並回傳,同時寫回緩存;沒找到進入下一步。
  5. 啟動非同步執行緒從網路下載。
  6. 下載成功後同時寫入磁碟與記憶體,並顯示到 UI。

配置入口

 File cacheDir = StorageUtils.getCacheDirectory(context, "UniversalImageLoader/Cache"); ImageLoaderConfiguration config = new ImageLoaderConfiguration .Builder(getApplicationContext()) .maxImageWidthForMemoryCache() .maxImageHeightForMemoryCache() .httpConnectTimeout() .httpReadTimeout() .threadPoolSize() .threadPriority(Thread.MIN_PRIORITY + ) .denyCacheImageMultipleSizesInMemory() .memoryCache(new UsingFreqLimitedCache()) // 你可以傳入自己的內存緩存 .discCache(new UnlimitedDiscCache(cacheDir)) // 你可以傳入自己的磁盤緩存 .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) .build(); 

記憶體緩存策略有哪些

只用強引用: LruMemoryCache,也就是預設實作。

強引用搭配弱引用:

  • UsingFreqLimitedMemoryCache:超過上限時刪除使用頻率最低的。
  • LRULimitedMemoryCache:同樣是 LRU 概念,但存的是弱引用。
  • FIFOLimitedMemoryCache:先進先出。
  • LargestLimitedMemoryCache:超過上限時先刪最大的那張。
  • LimitedAgeMemoryCache:超過存活時間就刪除。

只用弱引用: WeakMemoryCache,容量不限,但穩定性差,圖片容易被回收掉。

LruMemoryCache 的 get 與 put

預設配置由 ImageLoaderConfiguration.createDefault() 產生,記憶體用 LruMemoryCache、磁碟用 UnlimitedDiscCache。先看 get:

 /** * Returns the Bitmap for {@code key} if it exists in the cache. If a Bitmap was returned, it is moved to the head * of the queue. This returns null if a Bitmap is not cached. */ @Override public final Bitmap get(String key) { if (key == null) { throw new NullPointerException("key == null"); } synchronized (this) { return map.get(key); } } 

看起來只是從 map 取值,那「保留最近使用過的」是怎麼做到的?關鍵在 map 的型別——它是 LinkedHashMap<String, Bitmap>。LinkedHashMap 的 get 除了回傳值,還會在 accessOrder == true 時把該 entry 移到鏈表尾端;若為 false 則不動位置。

 @Override public V get(Object key) { /* * This method is overridden to eliminate the need for a polymorphic * invocation in superclass at the expense of code duplication. */ if (key == null) { HashMapEntry<K, V> e = entryForNullKey; if (e == null) return null; if (accessOrder) makeTail((LinkedEntry<K, V>) e); return e.value; } // Replace with Collections.secondaryHash when the VM is fast enough (https://b/). int hash = secondaryHash(key); HashMapEntry<K, V>[] tab = table; for (HashMapEntry<K, V> e = tab[hash & (tab.length - )]; e != null; e = e.next) { K eKey = e.key; if (eKey == key || (e.hash == hash && key.equals(eKey))) { if (accessOrder) makeTail((LinkedEntry<K, V>) e); return e.value; } } return null; }

makeTail() 就是調整雙向鏈表中 entry 的位置。所以每次 get 或 put 之後,被存取的項目都會被移到尾端,鏈表頭則始終是「最久沒被用到」的那一個。

再看 put:

 @Override public final boolean put(String key, Bitmap value) { if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } synchronized (this) { size += sizeOf(key, value); //map.put()的返回值如果不為空,說明存在跟key對應的entry,put操作只是更新原有key對應的entry Bitmap previous = map.put(key, value); if (previous != null) { size -= sizeOf(key, previous); } } trimToSize(maxSize); return true; }

size 是目前已用容量,每次 put 後呼叫 trimToSize(maxSize) 來做淘汰:

 private void trimToSize(int maxSize) { while (true) { String key; Bitmap value; synchronized (this) { if (size < || (map.isEmpty() && size != )) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } if (size <= maxSize || map.isEmpty()) { break; } Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator().next(); if (toEvict == null) { break; } key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); size -= sizeOf(key, value); } } }

這裡的關鍵是 map.entrySet().iterator().next()——因為 LinkedHashMap 以插入/存取順序維護鏈表,迭代的第一個元素就是鏈表頭,也就是最久未使用的項目。所以「遍歷一次就能淘汰最舊的」並不會誤刪剛用過的圖片。切記這裡定義的「最近使用」包含 get 與 put 兩種操作。

磁碟緩存有什麼選擇

對新浪微博、花瓣這類圖片量大的應用來說,磁碟緩存良善與否直接影響留存率——如果每次開 App 都要重新下載,使用者的流量會先把人趕走。

  • FileCountLimitedDiscCache:限制檔案數,超過就刪最早加入的。
  • LimitedAgeDiscCache:限制存活時間,超過就刪。
  • TotalSizeLimitedDiscCache:限制總容量,超過就刪最早加入的。
  • UnlimitedDiscCache:完全不限制。

BaseDiscCache 的建構與檔名

UnlimitedDiscCache 幾乎是空殼,只繼承 BaseDiscCache,所以直接看後者。建構子有三個參數:

 public BaseDiscCache(File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator) { if (cacheDir == null) { throw new IllegalArgumentException("cacheDir" + ERROR_ARG_NULL); } if (fileNameGenerator == null) { throw new IllegalArgumentException("fileNameGenerator" + ERROR_ARG_NULL); } this.cacheDir = cacheDir; this.reserveCacheDir = reserveCacheDir; this.fileNameGenerator = fileNameGenerator; }

cacheDir 是主緩存目錄,reserveCacheDir 可為 null、只有在 cacheDir 不可用時才派上用場,fileNameGenerator 負責產生檔名。預設的實作單純得令人意外:

 public class HashCodeFileNameGenerator implements FileNameGenerator { @Override public String generate(String imageUri) { return String.valueOf(imageUri.hashCode()); } }

save:先寫暫存檔再改名

 public boolean save(String imageUri, InputStream imageStream, IoUtils.CopyListener listener) throws IOException { File imageFile = getFile(imageUri); File tmpFile = new File(imageFile.getAbsolutePath() + TEMP_IMAGE_POSTFIX); boolean loaded = false; try { OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile), bufferSize); try { loaded = IoUtils.copyStream(imageStream, os, listener, bufferSize); } finally { IoUtils.closeSilently(os); } } finally { IoUtils.closeSilently(imageStream); if (loaded && !tmpFile.renameTo(imageFile)) { loaded = false; } if (!loaded) { tmpFile.delete(); } } return loaded; }

有人會問:為什麼 save 裡沒有判斷檔案是否已存在?答案是上層已經處理過了。UIL 的載入流程會先查記憶體、再查磁碟,都沒有才下載並呼叫 save,因此進到這個方法時,可以視為該檔確實不在磁碟上。

getFile:cacheDir 與 reserveCacheDir 的關係

 protected File getFile(String imageUri) { String fileName = fileNameGenerator.generate(imageUri); File dir = cacheDir; if (!cacheDir.exists() && !cacheDir.mkdirs()) { if (reserveCacheDir != null && (reserveCacheDir.exists() || reserveCacheDir.mkdirs())) { dir = reserveCacheDir; } } return new File(dir, fileName); }

邏輯一目了然:主目錄不存在且建立失敗,就改用 reserveCacheDir。最後回傳的 File 物件只是路徑的封裝,檔案實際存不存在要另外判斷——這點在呼叫端很容易忽略。

小結

看完就會發現,UIL 的緩存機制其實不神秘:記憶體緩存就是拿一個 Map 在記憶體裡存 Bitmap,只是換了不同的淘汰策略;磁碟緩存就是把檔案寫進去,再依容量、數量或時間決定何時刪。真正花心思的地方在於那些容易出錯的邊角——檔名衝突、暫存檔、目錄失效的退路。這些才是值得借鏡的部分。

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