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

Android 圖片與網路資料緩存:LRU + 軟引用 + 磁碟持久化

編輯:關於 Android 程式設計

列表滑動時反覆下載同一張圖,是流量與效能的雙重浪費。本文分享一套自製的緩存管理器 NetCacheManager,它同時具備四個特性:

  • 以 LinkedHashMap 實作 LRU(最近最少使用)淘汰,預設上限 4 MB,可透過 setMaxCacheSize 調整。
  • 用 SoftReference 包住資料,記憶體吃緊時交給虛擬機回收,不會直接 OOM。
  • 透過 ReferenceQueue 偵測已被回收的物件,並即時重算實際緩存大小,清掉「屍位」。
  • 支援內存與磁碟兩層緩存,並保留 ETag、Last-Modified 以便後續跟伺服器做條件式比對。

一、網路資料的包裝類

把 byte 陣列連同 HTTP 的驗證資訊一起包起來,下次請求就能帶回去問伺服器「這份有沒有變」。

package cc.util.cache;

import java.io.Serializable;
import java.util.Objects;

public class NetByteWrapper implements Serializable {

    private static final long serialVersionUID = 1L;

    private byte[] data;          // 網路取得的內容
    private long lastModified;    // 最後修改時間
    private String ETag;          // HTTP ETag

    public NetByteWrapper(byte[] data, long lastModified, String eTag) {
        this.data = data;
        this.lastModified = lastModified;
        this.ETag = eTag;
    }

    public byte[] getData() { return data; }
    public long getLastModified() { return lastModified; }
    public String getETag() { return ETag; }

    public int getContentLength() {
        return Objects.isNull(data) ? 0 : data.length;
    }
}

二、軟引用包裝

package cc.util.cache;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

public class NetByteSoftReference extends SoftReference<NetByteWrapper> {

    private final String key;
    private final long length;

    public NetByteSoftReference(String key, NetByteWrapper value) {
        this(key, value, null);
    }

    public NetByteSoftReference(String key, NetByteWrapper value,
                                ReferenceQueue<? super NetByteWrapper> queue) {
        super(value, queue);
        this.key = key;
        this.length = value.getContentLength();
    }

    public String getKey()   { return key; }
    public long getLength()  { return length; }
}

三、緩存管理器主體

package cc.util.cache;

import java.io.*;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Objects;

public class NetCacheManager {

    private long MAX_CACHE_SIZE = 4 * 1024 * 1024;
    private long cacheSize = 0;

    private static NetCacheManager instance = null;

    private final ReferenceQueue<NetByteWrapper> referenceQueue;
    private final LinkedHashMap<String, NetByteSoftReference> cacheMap;

    private NetCacheManager() {
        referenceQueue = new ReferenceQueue<NetByteWrapper>();
        cacheMap = new LinkedHashMap<String, NetByteSoftReference>(16, 0.75f, true) {
            private static final long serialVersionUID = -8378285623387632829L;

            @Override
            protected boolean removeEldestEntry(
                    java.util.Map.Entry<String, NetByteSoftReference> eldest) {
                boolean shouldRemove = cacheSize > MAX_CACHE_SIZE;
                if (shouldRemove) {
                    cacheSize -= eldest.getValue().getLength();
                    System.gc();
                }
                return shouldRemove;
            }
        };
    }

    /** 單例 */
    public static synchronized NetCacheManager newInstance() {
        if (Objects.isNull(instance)) {
            instance = new NetCacheManager();
        }
        return instance;
    }

    public void setMaxCacheSize(long cacheSize) { this.MAX_CACHE_SIZE = cacheSize; }
    public long getCacheSize() { return cacheSize; }

    /** 寫入內存緩存,key 一般就是請求的 URL */
    public void cacheInMemory(String key, byte[] value) {
        cacheInMemory(key, value, 0, null);
    }

    public void cacheInMemory(String key, byte[] value, long lastModified) {
        cacheInMemory(key, value, lastModified, null);
    }

    public void cacheInMemory(String key, byte[] value, String eTags) {
        cacheInMemory(key, value, 0, eTags);
    }

    private void cacheInMemory(String key, byte[] value, long lastModified, String eTags) {
        Objects.requireNonNull(key, "key must not be null");
        clearRecycledObject();
        NetByteWrapper wrapper = new NetByteWrapper(value, lastModified, eTags);
        cacheMap.put(key, new NetByteSoftReference(key, wrapper, referenceQueue));
    }

    /** 寫入磁碟,可選擇同時寫一份到內存 */
    public void cacheInDisk(String key, byte[] value, String path) {
        cacheInDisk(key, value, path, false);
    }

    public void cacheInDisk(String key, byte[] value, String path, boolean cacheInMemory) {
        cacheInDisk(key, value, 0, null, path, cacheInMemory);
    }

    private void cacheInDisk(String key, byte[] value, long lastModified, String eTags,
                             String path, boolean cacheInMemory) {
        if (cacheInMemory) {
            cacheInMemory(key, value, lastModified, eTags);
        }
        try (FileOutputStream fos = new FileOutputStream(path);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(new NetByteWrapper(value, lastModified, eTags));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public NetByteWrapper getFromMemory(String key) {
        SoftReference<NetByteWrapper> ref = cacheMap.get(key);
        return Objects.nonNull(ref) ? ref.get() : null;
    }

    public byte[] getByteFromMemory(String key) {
        NetByteWrapper wrapper = getFromMemory(key);
        return Objects.isNull(wrapper) ? null : wrapper.getData();
    }

    public NetByteWrapper getFromDisk(String path) {
        try (FileInputStream fis = new FileInputStream(path);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            return (NetByteWrapper) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 大檔案建議走記憶體映射,讀取速度明顯較快 */
    public NetByteWrapper getFromDiskByMapped(String path) {
        try (FileInputStream fis = new FileInputStream(path);
             FileChannel channel = fis.getChannel();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            byte[] bts = new byte[1024];
            int len = (int) channel.size();
            for (int offset = 0; offset < len; offset += 1024) {
                if (len - offset > 1024) {
                    mbb.get(bts);
                } else {
                    bts = new byte[len - offset];
                    mbb.get(bts);
                }
                baos.write(bts);
            }

            try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                 ObjectInputStream ois = new ObjectInputStream(bais)) {
                return (NetByteWrapper) ois.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] getByteFromDisk(String path) {
        NetByteWrapper wrapper = getFromDisk(path);
        return Objects.isNull(wrapper) ? null : wrapper.getData();
    }

    public byte[] getByteFromDiskByMapped(String path) {
        NetByteWrapper wrapper = getFromDiskByMapped(path);
        return Objects.isNull(wrapper) ? null : wrapper.getData();
    }

    /** 清掉已被虛擬機回收的項目,並重新統計實際大小 */
    private void clearRecycledObject() {
        NetByteSoftReference ref;
        while (Objects.nonNull((ref = (NetByteSoftReference) referenceQueue.poll()))) {
            cacheMap.remove(ref.getKey());
        }
        cacheSize = 0;
        Iterator<String> keys = cacheMap.keySet().iterator();
        while (keys.hasNext()) {
            cacheSize += cacheMap.get(keys.next()).getLength();
        }
    }

    /** 清空內存緩存 */
    public void clearCache() {
        clearRecycledObject();
        cacheMap.clear();
        System.gc();
        System.runFinalization();
    }
}

設計重點

把 LinkedHashMap 的第三個參數設為 true,會讓它依「存取順序」而非「插入順序」排列,這是 LRU 能成立的前提;再搭配 removeEldestEntry 做容量控制,就得到一個自帶淘汰策略的緩存池。

而 SoftReference 加上 ReferenceQueue 的組合,解決了另一個問題:記憶體不足時物件會被回收,但 map 裡的鍵還在,若直接用會拿到 null。有了 clearRecycledObject() 定期清理,統計出來的 cacheSize 才會準確,淘汰判斷也才不會失真。

使用上需注意,類別用到 Objects、MappedByteBuffer 與 try-with-resources,需 JDK 7 以上;另外 System.gc() 在每次淘汰時呼叫並不理想,正式專案建議移除,交給系統自行決定時機。

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