在阅读源码之前,我们先大致了解一下Volley运行的一些基本原理:Volley在启动之后会启动两种线程,分别是缓存调度线程和网络请求线程,默认情况下会创建4个网络请求线程组成线程池。Volley的请求队列,无论是准备就绪的网络请求队列还是缓存队列,都是采用优先级队列PriorityBlockingQueue进行存储的,所以Volley的网络请求是具有优先级控制功能的;由于Volley具有缓存调度,所以Volley是可以过滤重复的网络请求。我们可以在Volley的请求回调方法中安全的操作主线程,不需要担心Volley子线程引起的跨线程UI更新问题,这归功于Volley结果分发器为我们做了跨线程处理。
如果上面对Volley的原理简单介绍无法理解,不要紧,下来我们将围绕Volley的网络请求线程调度、缓存机制、优先级控制、结果分发器展开解析。
我们使用Volley时,是从newRequestQueue方法开始,那么我们就从Volley.newRequestQueue方法切入Volley的源码:
RequestQueue requestQueue = Volley.newRequestQueue(this);
newRequestQueue方法源码:
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = "volley/0";
try {
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (NameNotFoundException e) {
}
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
Network network = new BasicNetwork(stack);
RequestQueue queue;
if (maxDiskCacheBytes <= -1)
{
// No maximum size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
}
else
{
// Disk cache size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
}
queue.start();
return queue;
}
newRequestQueue的工作步骤:
1、newRequestQueue方法的第一行就是创建一个文件目录(文件夹),这个目录将用于缓存Volley的网络请求。接着,会根据系统的版本,分别创建HurlStack和HttpClientStack。这两个类就是Volley的网络请求类,它们将执行真正的网络请求操作。只不过,HurlStack底层调用的是HttpUrlConnection类来实现网络请求,而HttpClientStack是调用HttpClient类来实现网络请求,因为在API9以下,HttpUrlConnection类是存在Bug的,所以Volley在此做了兼容。我们之后对网络请求的分析将基于HurlStack类来展开。
2、接着创建BasicNetwork类,BasicNetwork实现了Network接口,它将负责把HurlStack类执行网络请求后的结果进一步加工处理。
3、最后创建RequestQueue类,并启动它。RequestQueue就是网络请求队列、缓存的集成中心,网络请求线程、缓存线程就是由他的start方法创建启动的。
由此,我们定位到RequestQueue的start方法:
public void start() {
stop(); // Make sure any currently running dispatchers are stopped.
// Create the cache dispatcher and start it.
mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
mCacheDispatcher.start();
// Create network dispatchers (and corresponding threads) up to the pool size.
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
mCache, mDelivery);
mDispatchers[i] = networkDispatcher;
networkDispatcher.start();
}
}
在start方法里面,先调用程序清除mCacheDispatcher和mDispatchers,接着在重新new创建新的mCacheDispatcher和mDispatchers。
那么mCacheDispatcher和mDispatchers是什么呢?
mCacheDispatcher是CacheDispatcher类,继承于Thread,它就是前面所说的缓存调度线程,在其run方法中进入死循环,不断的读取处理具有优先级性质的缓存队列中的请求。
mDispatchers也是NetworkDispatcher类,继承于Thread类,它就是网络请求调度线程,由mDispatchers.length个NetworkDispatcher组成网络请求调度线程池。
到这里,我们知道网络请求被压进请求队列和缓存队列,通过网络请求调度线程和缓存调度线程来处理他们,最终通过分发器回调到UI界面。那么,这些请求是怎么被压进队列里面的呢?回想一下,我们使用Volley的时候,除了创建RequestQueue之外,我们在进行网络请求的时候,会把创建Request add到RequestQueue中,所以,我们定位到RequestQueue的add方法:
public <T> Request<T> add(Request<T> request) {
// Tag the request as belonging to this queue and add it to the set of current requests.
request.setRequestQueue(this);
synchronized (mCurrentRequests) {
mCurrentRequests.add(request);
}
// Process requests in the order they are added.
request.setSequence(getSequenceNumber());
request.addMarker("add-to-queue");
// If the request is uncacheable, skip the cache queue and go straight to the network.
if (!request.shouldCache()) {
mNetworkQueue.add(request);
return request;
}
// Insert request into stage if there's already a request with the same cache key in flight.
synchronized (mWaitingRequests) {
String cacheKey = request.getCacheKey();
if (mWaitingRequests.containsKey(cacheKey)) {
// There is already a request in flight. Queue up.
Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);
if (stagedRequests == null) {
stagedRequests = new LinkedList<Request<?>>();
}
stagedRequests.add(request);
mWaitingRequests.put(cacheKey, stagedRequests);
if (VolleyLog.DEBUG) {
VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
}
} else {
// Insert 'null' queue for this cacheKey, indicating there is now a request in
// flight.
mWaitingRequests.put(cacheKey, null);
mCacheQueue.add(request);
}
return request;
}
}
由于网络调度线程池是由默认4个(mDispatchers.length)Thread的网络调度器组成的,所以这里用synchronized修饰同步块(第9行代码),把Request添加到当前队mCurrentRequests列里面。接着判断Request是否缓存的标志,若不需要缓存直接add到网络请求就绪队列mNetworkQueue里面直接准备进行网络请求操作;如果允许缓存,则会到阻塞队列mWaitingRequests里面查找是否存在,存在的话,刷新阻塞队列里面对应的Request;不存在的话,则把Request put进阻塞队列和缓存队列mCacheQueue。
那么阻塞队列mWaitingRequests是起什么作用的呢?缓存队列mCacheQueue会由CacheDispatcher去调度,“备份”一份在阻塞队列中,为何呢?回到阻塞队列声明的地方:
/**
* Staging area for requests that already have a duplicate request in flight.
*
* <ul>
* <li>containsKey(cacheKey) indicates that there is a request in flight for the given cache
* key.</li>
* <li>get(cacheKey) returns waiting requests for the given cache key. The in flight request
* is <em>not</em> contained in that list. Is null if no requests are staged.</li>
* </ul>
*/
private final Map<String, Queue<Request<?>>> mWaitingRequests =
new HashMap<String, Queue<Request<?>>>();
从他的英文注释中可以知道,这个阻塞队列是为了防止重复的Request。当有多个相同的Request请求发起,后续的相同的Request并不会产生新的Request,而是更新原来的第一个的Request信息。