1.活动缓存数据结构用的HashMap
final class ActiveResources {
@VisibleForTesting final Map<Key, ResourceWeakReference> activeEngineResources = new
HashMap<>();
}
2.内存缓存LinkedHashMap
public class LruCache<T, Y> {
private final Map<T, Entry<Y>> cache = new LinkedHashMap<>(100, 0.75f, true);
}
3.从活动或者内存缓存读取
public class Engine implements EngineJobListener, MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
private EngineResource<?> loadFromMemory( EngineKey key, boolean isMemoryCacheable,
long startTime) {
if (!isMemoryCacheable) {//是否支持内存缓存
return null;
}
EngineResource<?> active = loadFromActiveResources(key);//从活动缓存获取
if (active != null) {//如果活动缓存不为null
return active;
}
EngineResource<?> cached = loadFromCache(key);//从内存缓存获取
if (cached != null) { //如果内存缓存不为null
return cached;
}
return null;
}
}
4.从活动缓存获取
public class Engine
implements EngineJobListener,
MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
@Nullable
private EngineResource<?> loadFromActiveResources(Key key) {
EngineResource<?> active = activeResources.get(key); //从活动缓存获取
if (active != null) {
active.acquire();
}
return active;
}
}
5.从内存缓存获取
- 从活动缓存中移除这个元素
- 返回
- 将获得的元素放入活动缓存
public class Engine implements EngineJobListener, MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
private EngineResource<?> loadFromCache(Key key) {
EngineResource<?> cached = getEngineResourceFromCache(key); //获得内存缓存
if (cached != null) {
cached.acquire();
activeResources.activate(key, cached);//放入活动缓存
}
return cached;
}
}
public class Engine implements EngineJobListener, MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
private EngineResource<?> getEngineResourceFromCache(Key key) {
Resource<?> cached = cache.remove(key);//从内存缓存移除
final EngineResource<?> result; //返回的元素是新建的
if (cached == null) {
result = null;
} else if (cached instanceof EngineResource) {
// Save an object allocation if we've cached an EngineResource
//(the typical case).
result = (EngineResource<?>) cached;
} else {
result = new EngineResource<>(
cached,
/* isMemoryCacheable= */ true,
/* isRecyclable= */ true,
key,
/* listener= */ this);
}
return result;
}
}
6.总结
- 先从活动缓存读取;
- 如果活动缓存读取到的为null,再从内存缓存读取;
- 从内存缓存读取的时候,会将缓存的值从内存缓存移除,再放入活动缓存;