publicstaticDiskLruCachecreate(FileSystemfileSystem,Filedirectory,intappVersion,intvalueCount,longmaxSize){// Use a single background thread to evict entries.
// 创建了一个单线程的线程池
Executorexecutor=newThreadPoolExecutor(0,1,60L,TimeUnit.SECONDS,newLinkedBlockingQueue<Runnable>(),Util.threadFactory("OkHttp DiskLruCache",true));returnnewDiskLruCache(fileSystem,directory,appVersion,valueCount,maxSize,executor);}
// 看看,还是基于这玩意的「插入排序」实现的
finalLinkedHashMap<String,Entry>lruEntries=newLinkedHashMap<>(0,0.75f,true);// edit方法
synchronizedEditoredit(Stringkey,longexpectedSequenceNumber)throwsIOException{// 首先初始化
initialize();// 当前DiskLruCache的关闭检查,必须关闭之后才能edit。
checkNotClosed();// key的安全检查
validateKey(key);// 查询到对应的entry
Entryentry=lruEntries.get(key);if(expectedSequenceNumber!=ANY_SEQUENCE_NUMBER&&(entry==null||entry.sequenceNumber!=expectedSequenceNumber)){returnnull;// Snapshot is stale.
}if(entry!=null&&entry.currentEditor!=null){returnnull;// Another edit is in progress.
}if(mostRecentTrimFailed||mostRecentRebuildFailed){// The OS has become our enemy! If the trim job failed, it means we are storing more data than
// requested by the user. Do not allow edits so we do not go over that limit any further. If
// the journal rebuild failed, the journal writer will not be active, meaning we will not be
// able to record the edit, causing file leaks. In both cases, we want to retry the clean up
// so we can get out of this state!
//异步执行
executor.execute(cleanupRunnable);returnnull;}// Flush the journal before creating files to prevent file leaks.
journalWriter.writeUtf8(DIRTY).writeByte(' ').writeUtf8(key).writeByte('\n');journalWriter.flush();if(hasJournalErrors){returnnull;// Don't edit; the journal can't be written.
}if(entry==null){entry=newEntry(key);lruEntries.put(key,entry);}Editoreditor=newEditor(entry);entry.currentEditor=editor;returneditor;}
publicsynchronizedvoidinitialize()throwsIOException{assertThread.holdsLock(this);if(initialized){return;// Already initialized.
}// 从备份中恢复
if(fileSystem.exists(journalFileBackup)){// If journal file also exists just delete backup file.
if(fileSystem.exists(journalFile)){fileSystem.delete(journalFileBackup);}else{fileSystem.rename(journalFileBackup,journalFile);}}// Prefer to pick up where we left off.
if(fileSystem.exists(journalFile)){try{// 读取杂志文件
readJournal();processJournal();initialized=true;return;}catch(IOExceptionjournalIsCorrupt){Platform.get().log(WARN,"DiskLruCache "+directory+" is corrupt: "+journalIsCorrupt.getMessage()+", removing",journalIsCorrupt);}try{delete();}finally{closed=false;}}rebuildJournal();initialized=true;}