DiskBasedCache詳解

weixin_34413357發表於2018-07-14

DiskBasedCache詳解

首先我們來看看關於這個類的說明:

/**
 * Cache implementation that caches files directly onto the hard disk in the specified directory.
 * The default disk usage size is 5MB, but is configurable.
 *
 * <p>This cache supports the {@link Entry#allResponseHeaders} headers field.
 */

它是Cache介面的實現。作用是直接快取檔案到硬碟上指定的路徑。預設快取最大尺寸是5MB,不過這個大小是可以配置的。
檢視原始碼,我們知道,這個類實現了Cache這個介面。那麼,我們首先看看Cache的原始碼(有人可能會問,為啥?你想,一個類去實現某個介面,意味著這個類要實現這個介面的標準。同時說明這個類一定是和這個介面密切相關的)。

Cache

先看說明:

/** An interface for a cache keyed by a String with a byte array as data. */

它是:用字串陣列作為資料,以String作為Key的快取的介面。

import java.util.Collections;
import java.util.List;
import java.util.Map;

/** An interface for a cache keyed by a String with a byte array as data. */
public interface Cache {
    /**
     * Retrieves an entry from the cache.
     * 從快取中檢索條目。
     * @param key Cache key
     * @return An {@link Entry} or null in the event of a cache miss
     */
    Entry get(String key);

    /**
     * Adds or replaces an entry to the cache.
     * 將條目新增或替換到快取。
     * @param key Cache key
     * @param entry Data to store and metadata for cache coherency, TTL, etc.
     */
    void put(String key, Entry entry);

    /**
     * Performs any potentially long-running actions needed to initialize the cache; will be called
     * from a worker thread.
     * 執行初始化快取所需的任何可能長時間執行的操作; 將從工作執行緒呼叫。
     */
    void initialize();

    /**
     * Invalidates an entry in the cache.
     * 使快取中的條目無效。
     * @param key Cache key
     * @param fullExpire True to fully expire the entry, false to soft expire
     */
    void invalidate(String key, boolean fullExpire);

    /**
     * Removes an entry from the cache.
     * 從快取中刪除條目。
     * @param key Cache key
     */
    void remove(String key);

    /** Empties the cache. 清空快取。*/
    void clear();

    /** Data and metadata for an entry returned by the cache. 
     *  快取返回的條目的資料和後設資料。
     */
    class Entry {
        /** The data returned from cache. 從快取返回的資料。*/
        public byte[] data;

        /** ETag for cache coherency. ETag用於快取一致性。*/
        public String etag;

        /** Date of this response as reported by the server. 
         *  伺服器報告的響應日期。
         */
        public long serverDate;

        /** The last modified date for the requested object. 
         * 請求物件的上次修改日期。
         */
        public long lastModified;

        /** TTL for this record. 此記錄的TTL。*/
        public long ttl;

        /** Soft TTL for this record. 此記錄的軟TTL。*/
        public long softTtl;

        /**
         * Response headers as received from server; must be non-null. Should not be mutated
         * directly. 從伺服器收到的響應標頭; 必須是非null。 不應該直接轉變。
         *
         * <p>Note that if the server returns two headers with the same (case-insensitive) name,
         * this map will only contain the one of them. {@link #allResponseHeaders} may contain all
         * headers if the {@link Cache} implementation supports it.
         */
        public Map<String, String> responseHeaders = Collections.emptyMap();

        /**
         * All response headers. May be null depending on the {@link Cache} implementation. Should
         * not be mutated directly.
         */
        public List<Header> allResponseHeaders;

        /** True if the entry is expired. 如果條目已過期,則為True。*/
        public boolean isExpired() {
            return this.ttl < System.currentTimeMillis();
        }

        /** True if a refresh is needed from the original data source. 
         *  如果需要從原始資料來源進行重新整理,則為True。
         */
        public boolean refreshNeeded() {
            return this.softTtl < System.currentTimeMillis();
        }
    }
}

檢視註釋,比較容易理解,提供了幾個方法,分別用於:初始化,設定、獲取或移除Entry,清空快取。有一個內部類Entry需要了解一下,這個類記錄了快取內容(字串陣列),Tag用於標誌,伺服器響應的日誌,請求物件的上次修改日期,傳輸請求記錄的時間,伺服器響應的header。以及提供了一個方法使用者判斷條目是否過去,以及一個是否需要重新整理的方法。

內部類CountingInputStream

如果一個類中有一個內部類,說明這個內部類和自己的功能關係非常密切。那麼,我們在正式分析這個類的程式碼之前,一般要先分析這個內部類。這樣有利於我們讀懂程式碼。其實從原始檔上來看,我們應該先分析CacheHeader類,然而,我發現CacheHeader中呼叫了CountingInputStream,所以,我們就先分析它。嗯,貌似沒有寫註釋,應該是程式碼功能比較簡單。既然程式碼不長,我們直接讀程式碼。

    @VisibleForTesting
    static class CountingInputStream extends FilterInputStream {
        private final long length;
        private long bytesRead;

        CountingInputStream(InputStream in, long length) {
            super(in);
            this.length = length;
        }

        @Override
        public int read() throws IOException {
            int result = super.read();
            if (result != -1) {
                bytesRead++;
            }
            return result;
        }

        @Override
        public int read(byte[] buffer, int offset, int count) throws IOException {
            int result = super.read(buffer, offset, count);
            if (result != -1) {
                bytesRead += result;
            }
            return result;
        }

        @VisibleForTesting
        long bytesRead() {
            return bytesRead;
        }

        long bytesRemaining() {
            return length - bytesRead;
        }
    }

它繼承自FilterInputStream。對這個不熟的同學,可以看看這篇部落格
這個類只有一個建構函式。額,提一句,這就是java程式設計思想中的裝飾者模式。

    private final long length;

    CountingInputStream(InputStream in, long length) {
        super(in);
        this.length = length;
    }

比較簡單,就是設定了一個長度。這個長度的作用,我們暫時還不清楚,接下來再看看。
它重寫了兩個read()方法。作用就是從inputStream中讀取位元組陣列。不同的是第二個,有三個引數,分別是buffer,offset和count。作用是,buffer作為容器放置讀出來的內容,offset作為讀取出來的內容放在容器中的偏移位置,count表示想要讀取的長度。然後返回讀出來的位元組數量。同時在第二個重新read()方法中,如果發現本次讀取的內容不為空,則將內部變數byteRead記加讀取出來的位元組長度。
接下來的兩個方法是:

  • bytesRead() 作用是讀出來已經讀取的位元組長度
      @VisibleForTesting
      long bytesRead() {
          return bytesRead;
      }
    
  • bytesRemaining() 作用是看還剩餘待讀的位元組長度。在這,我們找到了建構函式中的length的作用了,用來計算還剩餘想要讀的位元組長度。
      long bytesRemaining() {
              return length - bytesRead;
      }
    

好了,我們分析完CountingInputStream類了,它的功能就是從inputStream中讀取出來以位元組為單位指定長度的資料。再看看另外一個內部類。

內部類CacheHeader

這個類的描述是:

/** Handles holding onto the cache headers for an entry. */

意思是:處理Header和Entry序列化和反序列化。但是,什麼是Header呢?

Header

這個Header其實就Http協議中的Header。從資料結構上來講是這樣的:

import android.text.TextUtils;

/** An HTTP header. */
public final class Header {
    private final String mName;
    private final String mValue;

    public Header(String name, String value) {
        mName = name;
        mValue = value;
    }

    public final String getName() {
        return mName;
    }

    public final String getValue() {
        return mValue;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Header header = (Header) o;

        return TextUtils.equals(mName, header.mName) && TextUtils.equals(mValue, header.mValue);
    }

    @Override
    public int hashCode() {
        int result = mName.hashCode();
        result = 31 * result + mValue.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "Header[name=" + mName + ",value=" + mValue + "]";
    }
}

嗯,就是和Map差不多,是成對出現的。有key和value。當然,在這裡的叫法是:name和value。比較簡單,建構函式就是以name和value為引數的。再回到CacheHeader。
這個類(CacheHeader)中,有一些內部變數很重要,如:size(這個用來表示CacheHeader標定的資料的大小),key(用來標識這個cache entry),etag(用於快取的一致性,額,可能不好理解,我們再看看再說),serverDate(伺服器報告的響應日期),lastModified(請求物件的上次修改日期),tll(此記錄的TTL),softTtl(此記錄的軟TTL),allResponseHeaders(所有的響應Header)。其實和Entry結構類似。

    // VisibleForTesting
    static class CacheHeader {
        /** The size of the data identified by this CacheHeader. (This is not serialized to disk. */
        long size;

        /** The key that identifies the cache entry. */
        final String key;

        /** ETag for cache coherence. */
        final String etag;

        /** Date of this response as reported by the server. */
        final long serverDate;

        /** The last modified date for the requested object. */
        final long lastModified;

        /** TTL for this record. */
        final long ttl;

        /** Soft TTL for this record. */
        final long softTtl;

        /** Headers from the response resulting in this cache entry. */
        final List<Header> allResponseHeaders;

        private CacheHeader(
                String key,
                String etag,
                long serverDate,
                long lastModified,
                long ttl,
                long softTtl,
                List<Header> allResponseHeaders) {
            this.key = key;
            this.etag = ("".equals(etag)) ? null : etag;
            this.serverDate = serverDate;
            this.lastModified = lastModified;
            this.ttl = ttl;
            this.softTtl = softTtl;
            this.allResponseHeaders = allResponseHeaders;
        }

        /**
         * Instantiates a new CacheHeader object.
         *
         * @param key The key that identifies the cache entry
         * @param entry The cache entry.
         */
        CacheHeader(String key, Entry entry) {
            this(
                    key,
                    entry.etag,
                    entry.serverDate,
                    entry.lastModified,
                    entry.ttl,
                    entry.softTtl,
                    getAllResponseHeaders(entry));
            size = entry.data.length;
        }

        private static List<Header> getAllResponseHeaders(Entry entry) {
            // If the entry contains all the response headers, use that field directly.
            if (entry.allResponseHeaders != null) {
                return entry.allResponseHeaders;
            }

            // Legacy fallback - copy headers from the map.
            return HttpHeaderParser.toAllHeaderList(entry.responseHeaders);
        }

        /**
         * Reads the header from a CountingInputStream and returns a CacheHeader object.
         *
         * @param is The InputStream to read from.
         * @throws IOException if fails to read header
         */
        static CacheHeader readHeader(CountingInputStream is) throws IOException {
            int magic = readInt(is);
            if (magic != CACHE_MAGIC) {
                // don't bother deleting, it'll get pruned eventually
                throw new IOException();
            }
            String key = readString(is);
            String etag = readString(is);
            long serverDate = readLong(is);
            long lastModified = readLong(is);
            long ttl = readLong(is);
            long softTtl = readLong(is);
            List<Header> allResponseHeaders = readHeaderList(is);
            return new CacheHeader(
                    key, etag, serverDate, lastModified, ttl, softTtl, allResponseHeaders);
        }

        /** Creates a cache entry for the specified data. */
        Entry toCacheEntry(byte[] data) {
            Entry e = new Entry();
            e.data = data;
            e.etag = etag;
            e.serverDate = serverDate;
            e.lastModified = lastModified;
            e.ttl = ttl;
            e.softTtl = softTtl;
            e.responseHeaders = HttpHeaderParser.toHeaderMap(allResponseHeaders);
            e.allResponseHeaders = Collections.unmodifiableList(allResponseHeaders);
            return e;
        }

        /** Writes the contents of this CacheHeader to the specified OutputStream. */
        boolean writeHeader(OutputStream os) {
            try {
                writeInt(os, CACHE_MAGIC);
                writeString(os, key);
                writeString(os, etag == null ? "" : etag);
                writeLong(os, serverDate);
                writeLong(os, lastModified);
                writeLong(os, ttl);
                writeLong(os, softTtl);
                writeHeaderList(allResponseHeaders, os);
                os.flush();
                return true;
            } catch (IOException e) {
                VolleyLog.d("%s", e.toString());
                return false;
            }
        }
    }

從建構函式中可以看到,其中一個建構函式以key和Entry為引數,呼叫另外一個建構函式來建立物件。接下來,我們發現它呼叫了DiskBasedCache中的幾個方法,我們這裡就先簡單看一下。

 /*
     * Homebrewed simple serialization system used for reading and writing cache
     * headers on disk. Once upon a time, this used the standard Java
     * Object{Input,Output}Stream, but the default implementation relies heavily
     * on reflection (even for standard types) and generates a ton of garbage.
     *
     * TODO: Replace by standard DataInput and DataOutput in next cache version.
     */

    /**
     * Simple wrapper around {@link InputStream#read()} that throws EOFException instead of
     * returning -1.
     */
    private static int read(InputStream is) throws IOException {
        int b = is.read();
        if (b == -1) {
            throw new EOFException();
        }
        return b;
    }

    static void writeInt(OutputStream os, int n) throws IOException {
        os.write((n >> 0) & 0xff);
        os.write((n >> 8) & 0xff);
        os.write((n >> 16) & 0xff);
        os.write((n >> 24) & 0xff);
    }

    static int readInt(InputStream is) throws IOException {
        int n = 0;
        n |= (read(is) << 0);
        n |= (read(is) << 8);
        n |= (read(is) << 16);
        n |= (read(is) << 24);
        return n;
    }

    static void writeLong(OutputStream os, long n) throws IOException {
        os.write((byte) (n >>> 0));
        os.write((byte) (n >>> 8));
        os.write((byte) (n >>> 16));
        os.write((byte) (n >>> 24));
        os.write((byte) (n >>> 32));
        os.write((byte) (n >>> 40));
        os.write((byte) (n >>> 48));
        os.write((byte) (n >>> 56));
    }

    static long readLong(InputStream is) throws IOException {
        long n = 0;
        n |= ((read(is) & 0xFFL) << 0);
        n |= ((read(is) & 0xFFL) << 8);
        n |= ((read(is) & 0xFFL) << 16);
        n |= ((read(is) & 0xFFL) << 24);
        n |= ((read(is) & 0xFFL) << 32);
        n |= ((read(is) & 0xFFL) << 40);
        n |= ((read(is) & 0xFFL) << 48);
        n |= ((read(is) & 0xFFL) << 56);
        return n;
    }

    static void writeString(OutputStream os, String s) throws IOException {
        byte[] b = s.getBytes("UTF-8");
        writeLong(os, b.length);
        os.write(b, 0, b.length);
    }

    static String readString(CountingInputStream cis) throws IOException {
        long n = readLong(cis);
        byte[] b = streamToBytes(cis, n);
        return new String(b, "UTF-8");
    }

    static void writeHeaderList(List<Header> headers, OutputStream os) throws IOException {
        if (headers != null) {
            writeInt(os, headers.size());
            for (Header header : headers) {
                writeString(os, header.getName());
                writeString(os, header.getValue());
            }
        } else {
            writeInt(os, 0);
        }
    }

    static List<Header> readHeaderList(CountingInputStream cis) throws IOException {
        int size = readInt(cis);
        if (size < 0) {
            throw new IOException("readHeaderList size=" + size);
        }
        List<Header> result =
                (size == 0) ? Collections.<Header>emptyList() : new ArrayList<Header>();
        for (int i = 0; i < size; i++) {
            String name = readString(cis).intern();
            String value = readString(cis).intern();
            result.add(new Header(name, value));
        }
        return result;
    }

    /**
     * Reads length bytes from CountingInputStream into byte array.
     *
     * @param cis input stream
     * @param length number of bytes to read
     * @throws IOException if fails to read all bytes
     */
    // VisibleForTesting
    static byte[] streamToBytes(CountingInputStream cis, long length) throws IOException {
        long maxLength = cis.bytesRemaining();
        // Length cannot be negative or greater than bytes remaining, and must not overflow int.
        if (length < 0 || length > maxLength || (int) length != length) {
            throw new IOException("streamToBytes length=" + length + ", maxLength=" + maxLength);
        }
        byte[] bytes = new byte[(int) length];
        new DataInputStream(cis).readFully(bytes);
        return bytes;
    }

這幾個方法的作用是序列化,用於將磁碟上讀取的內容,反序列化成物件。關於為什麼要這樣做,註釋中寫的很明白:Java的輸入輸出系統自帶的系列化功能依賴於反射,這樣會帶來一些垃圾。所以,它就自己造了個輪子。額,比較簡單吧,我就不詳講了。
然後在CacheHeader中,提供了幾個方法

private static List<Header> getAllResponseHeaders(Entry entry);

/**
 * Reads the header from a CountingInputStream and returns a CacheHeader object.
 *
 * @param is The InputStream to read from.
 * @throws IOException if fails to read header
 */
static CacheHeader readHeader(CountingInputStream is) throws IOException;

/** Creates a cache entry for the specified data. */
Entry toCacheEntry(byte[] data);

/** Writes the contents of this CacheHeader to the specified OutputStream. */
boolean writeHeader(OutputStream os);

註釋寫的很清楚,就是Header和Entry之間序列化和反序列化用的。

DiskBasedCache的建構函式

哈哈,分析完介面之後,我們來分析下建構函式。
有兩個建構函式。

    ......
    
    /** The root directory to use for the cache. */
    private final File mRootDirectory;

    /** The maximum size of the cache in bytes. */
    private final int mMaxCacheSizeInBytes;

    /** Default maximum disk usage in bytes. */
    private static final int DEFAULT_DISK_USAGE_BYTES = 5 * 1024 * 1024;

    /**
     * Constructs an instance of the DiskBasedCache at the specified directory.
     *
     * @param rootDirectory The root directory of the cache.
     * @param maxCacheSizeInBytes The maximum size of the cache in bytes.
     */
    public DiskBasedCache(File rootDirectory, int maxCacheSizeInBytes) {
        mRootDirectory = rootDirectory;
        mMaxCacheSizeInBytes = maxCacheSizeInBytes;
    }

    /**
     * Constructs an instance of the DiskBasedCache at the specified directory using the default
     * maximum cache size of 5MB.
     *
     * @param rootDirectory The root directory of the cache.
     */
    public DiskBasedCache(File rootDirectory) {
        this(rootDirectory, DEFAULT_DISK_USAGE_BYTES);
    }

    ......

兩個建構函式,區別是,第一個建構函式可以設定快取檔案的大小。第一個引數用於設定快取檔案的路徑。所有請求的檔案都將放在該路徑下。建構函式僅僅是對內部變數賦值,應該還有別的方法來初始化其它變數。

initialize()方法

我們來看看Cache介面中定義的初始化方法-initialize()。這個方法的說明是:通過掃描當前位於指定根目錄中的所有檔案來初始化DiskBasedCache。 如有必要,建立根目錄。需要注意的是,這個方法加了同步關鍵字,這意味著,多執行緒操作時,不會被同時呼叫。

    /**
     * Initializes the DiskBasedCache by scanning for all files currently in the specified root
     * directory. Creates the root directory if necessary.
     */
    @Override
    public synchronized void initialize() {
        //判斷根路徑是否存在,如果不存在就建立一個。如果建立失敗,就打出異常。然後直接返回。
        if (!mRootDirectory.exists()) {
            if (!mRootDirectory.mkdirs()) {
                VolleyLog.e("Unable to create cache dir %s", mRootDirectory.getAbsolutePath());
            }
            return;
        }
        // 獲取根目錄下的檔案和資料夾
        File[] files = mRootDirectory.listFiles();
        if (files == null) {
            return;
        }
        //遍歷檔案列表,然後,將這些快取檔案的索引加入到快取列表中
        for (File file : files) {
            try {
                //獲取檔案的長度
                long entrySize = file.length();
                //根據檔案的長度和檔名建立一個CountingInputSteam。兩個入參,一個是CountingInputSteam,由createInputStream建立,另外一個是entry檔案的大小。
                CountingInputStream cis =
                        new CountingInputStream(
                                new BufferedInputStream(createInputStream(file)), entrySize);
                try {
                    //根據CountingInputStream讀取Header.
                    CacheHeader entry = CacheHeader.readHeader(cis);
                    // NOTE: When this entry was put, its size was recorded as data.length, but
                    // when the entry is initialized below, its size is recorded as file.length()
                    entry.size = entrySize;
                    //將entryc儲存在mEntries中
                    putEntry(entry.key, entry);
                } finally {
                    // Any IOException thrown here is handled by the below catch block by design.
                    //noinspection ThrowFromFinallyBlock
                    cis.close();
                }
            } catch (IOException e) {
                //noinspection ResultOfMethodCallIgnored
                file.delete();
            }
        }
    }

initialize()方法中,首先判斷根路徑是否存在,如果不存在就建立一個。如果建立失敗,就打出異常。然後直接返回。接著遍歷檔案列表,然後,將這些快取檔案的索引加入到快取列表(mEntries)中。在這個將磁碟本間快取到記憶體中的過程中,首先獲取檔案長度,然後根據檔名和長度,建立CountingInputStream,利用它反序列化成CacheHeader。然後電泳putEntry將這個entry儲存到記憶體變數mEntries中去。就這樣整個初始化就完成了。
這個過程中,呼叫了幾個方法。原始碼如下:

    // VisibleForTesting
    InputStream createInputStream(File file) throws FileNotFoundException {
        return new FileInputStream(file);
    }

    /**
     * Puts the entry with the specified key into the cache.
     *
     * @param key The key to identify the entry by.
     * @param entry The entry to cache.
     */
    private void putEntry(String key, CacheHeader entry) {
        if (!mEntries.containsKey(key)) {
            mTotalSize += entry.size;
        } else {
            CacheHeader oldEntry = mEntries.get(key);
            mTotalSize += (entry.size - oldEntry.size);
        }
        mEntries.put(key, entry);
    }

    /** Removes the entry identified by 'key' from the cache. */
    private void removeEntry(String key) {
        CacheHeader removed = mEntries.remove(key);
        if (removed != null) {
            mTotalSize -= removed.size;
        }
    }

以上方法不是很難,我們比較容易理解,不仔細講。
接下來,我們需要講對於DiskBasedCache最關鍵的部分,根據key,設定和獲取Entry方法。

set()方法

顧名思義,這個方法的作用是,將網路請求載入好的Entry,快取起來。看看原始碼吧。

    
    /** Puts the entry with the specified key into the cache. */
    @Override
    public synchronized void put(String key, Entry entry) {
        pruneIfNeeded(entry.data.length);
        File file = getFileForKey(key);
        try {
            BufferedOutputStream fos = new BufferedOutputStream(createOutputStream(file));
            CacheHeader e = new CacheHeader(key, entry);
            boolean success = e.writeHeader(fos);
            if (!success) {
                fos.close();
                VolleyLog.d("Failed to write header for %s", file.getAbsolutePath());
                throw new IOException();
            }
            fos.write(entry.data);
            fos.close();
            putEntry(key, e);
            return;
        } catch (IOException e) {
        }
        boolean deleted = file.delete();
        if (!deleted) {
            VolleyLog.d("Could not clean up file %s", file.getAbsolutePath());
        }
    }

    /**
     * Prunes the cache to fit the amount of bytes specified.
     *
     * @param neededSpace The amount of bytes we are trying to fit into the cache.
     */
    private void pruneIfNeeded(int neededSpace) {
        if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
            return;
        }
        if (VolleyLog.DEBUG) {
            VolleyLog.v("Pruning old cache entries.");
        }

        long before = mTotalSize;
        int prunedFiles = 0;
        long startTime = SystemClock.elapsedRealtime();

        Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, CacheHeader> entry = iterator.next();
            CacheHeader e = entry.getValue();
            boolean deleted = getFileForKey(e.key).delete();
            if (deleted) {
                mTotalSize -= e.size;
            } else {
                VolleyLog.d(
                        "Could not delete cache entry for key=%s, filename=%s",
                        e.key, getFilenameForKey(e.key));
            }
            iterator.remove();
            prunedFiles++;

            if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {
                break;
            }
        }

        if (VolleyLog.DEBUG) {
            VolleyLog.v(
                    "pruned %d files, %d bytes, %d ms",
                    prunedFiles, (mTotalSize - before), SystemClock.elapsedRealtime() - startTime);
        }
    }
    
    // VisibleForTesting
    OutputStream createOutputStream(File file) throws FileNotFoundException {
        return new FileOutputStream(file);
    }

    /**
     * Creates a pseudo-unique filename for the specified cache key.
     *
     * @param key The key to generate a file name for.
     * @return A pseudo-unique filename.
     */
    private String getFilenameForKey(String key) {
        int firstHalfLength = key.length() / 2;
        String localFilename = String.valueOf(key.substring(0, firstHalfLength).hashCode());
        localFilename += String.valueOf(key.substring(firstHalfLength).hashCode());
        return localFilename;
    }

    /** Returns a file object for the given cache key. */
    public File getFileForKey(String key) {
        return new File(mRootDirectory, getFilenameForKey(key));
    }

我們知道,快取是以key-value的方式儲存的。所以,這個方法的引數有兩個,分別是key和entry。
在快取之前,我們首先判斷一下本地快取是否超過檔案大小限制了,這在pruneIfNeeded()方法中完成。這個方法有一個入參,表示你需要快取的檔案大小。在這裡取的是entry.data.length。這個清除快取的演算法很有趣,沒有判斷快取時間,直接從mEntries中,一個個的遍歷,從第一個開始,刪掉它,然後判斷夠不夠用,不夠,再刪,直到夠用。嗯,總感覺這樣太粗暴了的說。
快取空間夠了之後,呼叫getFileForKey()方法,根據key,建立一個File。根據File建立一個BufferedOutputStream。利用這個Stream,建立一個CacheHeader。接著呼叫CacheHeader的writeHeader方法,將header寫入BufferedOutputStream。最後,將entry.data寫入BufferedOutputStream流中。這樣就完成了磁碟儲存。最終,呼叫putEntry()將entry寫入記憶體索引中。
好了,這就是set()方法。再來看看get()方法。

get()方法

還是直接看原始碼

    /** Returns the cache entry with the specified key if it exists, null otherwise. */
    @Override
    public synchronized Entry get(String key) {
        CacheHeader entry = mEntries.get(key);
        // if the entry does not exist, return.
        if (entry == null) {
            return null;
        }
        File file = getFileForKey(key);
        try {
            CountingInputStream cis =
                    new CountingInputStream(
                            new BufferedInputStream(createInputStream(file)), file.length());
            try {
                CacheHeader entryOnDisk = CacheHeader.readHeader(cis);
                if (!TextUtils.equals(key, entryOnDisk.key)) {
                    // File was shared by two keys and now holds data for a different entry!
                    VolleyLog.d(
                            "%s: key=%s, found=%s", file.getAbsolutePath(), key, entryOnDisk.key);
                    // Remove key whose contents on disk have been replaced.
                    removeEntry(key);
                    return null;
                }
                byte[] data = streamToBytes(cis, cis.bytesRemaining());
                return entry.toCacheEntry(data);
            } finally {
                // Any IOException thrown here is handled by the below catch block by design.
                //noinspection ThrowFromFinallyBlock
                cis.close();
            }
        } catch (IOException e) {
            VolleyLog.d("%s: %s", file.getAbsolutePath(), e.toString());
            remove(key);
            return null;
        }
    }

首先根據key,讀取記憶體中快取的檔案。然後根據這個key獲取到檔案,這樣將快取中的entry的header讀出來。然後判斷這連個key是否一樣,如果一樣,則將檔案流中剩餘的data讀出來。根據這個data和記憶體中的entry,建立一個新的entry,並返回。
除了set和get之外,它還提供了其它幾個方法,不是很難,直接給程式碼,大家可以自己分析。

    /**
     * Invalidates an entry in the cache.
     *
     * @param key Cache key
     * @param fullExpire True to fully expire the entry, false to soft expire
     */
    @Override
    public synchronized void invalidate(String key, boolean fullExpire) {
        Entry entry = get(key);
        if (entry != null) {
            entry.softTtl = 0;
            if (fullExpire) {
                entry.ttl = 0;
            }
            put(key, entry);
        }
    }

    /** Removes the specified key from the cache if it exists. */
    @Override
    public synchronized void remove(String key) {
        boolean deleted = getFileForKey(key).delete();
        removeEntry(key);
        if (!deleted) {
            VolleyLog.d(
                    "Could not delete cache entry for key=%s, filename=%s",
                    key, getFilenameForKey(key));
        }
    }
        
    /** Removes the entry identified by 'key' from the cache. */
    private void removeEntry(String key) {
        CacheHeader removed = mEntries.remove(key);
        if (removed != null) {
            mTotalSize -= removed.size;
        }
    }