CacheDispatcher提供线程来执行在请求队列上缓存级别的请求。缓存分发器也是一个线程类:
public class CacheDispatcher extends Thread
下面来看看它的成员变量以及作用
/**控制日志打印*/
private static final boolean DEBUG = VolleyLog.DEBUG;
/** The queue of requests coming in for triage. */
private final BlockingQueue<Request<?>> mCacheQueue;
/**请求网络的请求队列*/
private final BlockingQueue<Request<?>> mNetworkQueue;
/** 用于读取缓存 */
private final Cache mCache;
/** 用于发送响应内容 */
private final ResponseDelivery mDelivery;
/** 用来标记CacheDispatcher是否结束*/
private volatile boolean mQuit = false;
同样我们也最关心的是它的run方法:
@Override
public void run() {
if (DEBUG) VolleyLog.v("start new dispatcher");
//设置线程优先级
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// 初始化缓存
mCache.initialize();
//循环不断取出请求队列的请求
while (true) {
try {
// 从缓存级别队列获取请求
final Request<?> request = mCacheQueue.take();
request.addMarker("cache-queue-take");
// 如果获取到的请求已经被取消就不要分发此请求,接着获取下一个请求
if (request.isCanceled()) {
request.finish("cache-discard-canceled");
continue;
}
// 获取取出的请求在缓存区缓存的内容
Cache.Entryentry=mCache.get(request.getCacheKey());
if (entry == null) {//缓存区没有对应缓存内容,说明丢失了缓存,那么网络分发器对此请求入队
request.addMarker("cache-miss");
mNetworkQueue.put(request);
continue;
}
//缓存内容存在,但是已经失效,网络分发器对此请求入队
if (entry.isExpired()) {
request.addMarker("cache-hit-expired");
request.setCacheEntry(entry);
mNetworkQueue.put(request);
continue;
}
// 高速缓存命中; 把此请求的数据解析出来传递给请求自身
request.addMarker("cache-hit");
Response<?> response = request.parseNetworkResponse(
new NetworkResponse(entry.data, entry.responseHeaders));
request.addMarker("cache-hit-parsed");
//是否需要刷新缓存的内容
if (!entry.refreshNeeded()) {
//完全未到期高速缓存命中,传递缓存内容
mDelivery.postResponse(request, response);
} else {
request.addMarker("cache-hit-refresh-needed");
request.setCacheEntry(entry);
response.intermediate = true;
//传递响应内容同时网络分发器将请求入队
mDelivery.postResponse(request, response, new Runnable() {
@Override
public void run() {
try {
mNetworkQueue.put(request);
} catch (InterruptedException e) {
// Not much we can do about this.
}
}
});
}
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
continue;
}
}
}