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就可以了