Glide緩存機制

1.LinkedHashMap——http://blog.csdn.net/lxj1137800599/article/details/54976180
2.cleanupCallable(涉及到ThreadPoolExecutor——http://blog.csdn.net/lxj1137800599/article/details/55808019

private final Callable<Void> cleanupCallable = new Callable<Void>() {
        public Void call() throws Exception {
            synchronized (DiskLruCache.this) {
                if (journalWriter == null) {
                    return null; // Closed.
                }
                trimToSize();
                if (journalRebuildRequired()) {
                    rebuildJournal();
                    redundantOpCount = 0;
                }
            }
            return null;
        }
    };

重點在trimToSize上(maxSize是構造函數傳入的,size指的是所有entry裏面file的總長度)

private void trimToSize() throws IOException {
        while (size > maxSize) {
            Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();//爲什麼刪除第一個?lruEntries是LinkedHashMap
            remove(toEvict.getKey());
        }
    }

先把size減小,然後把緩存文件置空,最後remove key

public synchronized boolean remove(String key) throws IOException {
        checkNotClosed();
        Entry entry = lruEntries.get(key);
        if (entry == null || entry.currentEditor != null) {
            return false;
        }

        for (int i = 0; i < valueCount; i++) {
            File file = entry.getCleanFile(i);
            if (file.exists() && !file.delete()) {
                throw new IOException("failed to delete " + file);
            }
            size -= entry.lengths[i];
            entry.lengths[i] = 0;
        }

        redundantOpCount++;
        journalWriter.append(REMOVE);
        journalWriter.append(' ');
        journalWriter.append(key);
        journalWriter.append('\n');

        lruEntries.remove(key);

        if (journalRebuildRequired()) {
            executorService.submit(cleanupCallable);
        }

        return true;
    }

總結,由於LinkedHashMap的特殊性,完全沒有必要增加線程池等操作,直接remove就可以了

發佈了223 篇原創文章 · 獲贊 23 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章