一、内存缓存实现
com.bumptech.glide.util.LruCache<T, Y>中,通过LinkedHashMap做内存缓存
Engine中,MemoryCache.put(EngineKey, EngineResource);添加到LinkedHashMap中。
EngineKey组成:
public EngineKey(String id, Key signature, int width, int height, ResourceDecoder cacheDecoder, ResourceDecoder decoder,
Transformation transformation, ResourceEncoder encoder, ResourceTranscoder transcoder, Encoder sourceEncoder) {
this.id = id;
this.signature = signature;
this.width = width;
this.height = height;
this.cacheDecoder = cacheDecoder;
this.decoder = decoder;
this.transformation = transformation;
this.encoder = encoder;
this.transcoder = transcoder;
this.sourceEncoder = sourceEncoder;
}
EngineResource组成:
EngineResource(Resource<Z> toWrap, boolean isCacheable) {
if (toWrap == null) {
throw new NullPointerException("Wrapped resource must not be null");
}
resource = toWrap;
this.isCacheable = isCacheable;
}
加载图片前,在Engine中先从缓存取,取不到才会去下载
二、磁盘缓存
有个只有一个线程的线程池,扫描日志文件,根据日志文件的日志对缓存做处理
//只有一个线程的线程池,在后台扫描日志文件,根据日志信息操作缓存
final ThreadPoolExecutor executorService = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
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;
}
};
DiskLruCache 下载图片成功后,会走磁盘缓存 DecodeJob.java中
public Resource<Z> decodeFromSource() throws Exception {
Resource<T> decoded = decodeSource();//解码后的资源
return transformEncodeAndTranscode(decoded);
}
private Resource<Z> transformEncodeAndTranscode(Resource<T> decoded) {
long startTime = LogTime.getLogTime();
Resource<T> transformed = transform(decoded);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Transformed resource from source", startTime);
}
writeTransformedToCache(transformed);//把解码后的资源写入缓存
startTime = LogTime.getLogTime();
Resource<Z> result = transcode(transformed);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Transcoded transformed from source", startTime);
}
return result;
}
private void writeTransformedToCache(Resource<T> transformed) {
if (transformed == null || !diskCacheStrategy.cacheResult()) {
return;
}
long startTime = LogTime.getLogTime();
//这个writer会把解码的资源,重新编码写入文件