publicclassRequestQueue { // 用来保存有相同Url的Request,因为对于可以缓存的Request来说,Url相同,意味着Response也应该相同 // 对于这类Request只需要请求一次即可,这是Volley优化点之一 privatefinal Map<String, Queue<Request<?>>> mWaitingRequests = newHashMap<String, Queue<Request<?>>>(); /** * The set of all requests currently being processed by this RequestQueue. A Request * will be in this set if it is waiting in any queue or currently being processed by * any dispatcher. * 保存正在处理或者正在等待的请求 */ privatefinal Set<Request<?>> mCurrentRequests = newHashSet<Request<?>>(); // 缓存队列,参考mWaitingRequests,该队列中的Request会交给CacheDispatcher进行处理 privatefinal PriorityBlockingQueue<Request<?>> mCacheQueue = newPriorityBlockingQueue<Request<?>>(); // 所有使用add方法添加的请求都会放在这里 privatefinal PriorityBlockingQueue<Request<?>> mNetworkQueue = newPriorityBlockingQueue<Request<?>>(); // 负责分发响应结果,同时把结果投递到主线程中 privatefinal ResponseDelivery mDelivery; publicvoidstart() { stop(); // Make sure any currently running dispatchers are stopped. // Create the cache dispatcher and start it. mCacheDispatcher = newCacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery); mCacheDispatcher.start(); // Create network dispatchers (and corresponding threads) up to the pool size. for (inti=0; i < mDispatchers.length; i++) { NetworkDispatchernetworkDispatcher=newNetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery); mDispatchers[i] = networkDispatcher; networkDispatcher.start(); } } }
publicclassRequestQueue { /** * Adds a Request to the dispatch queue. * @param request The request to service * @return The passed-in request */ 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); } // 添加标记 request.setSequence(getSequenceNumber()); request.addMarker("add-to-queue"); // 如果不需要缓存,直接把请求添加到网络队列中 if (!request.shouldCache()) { mNetworkQueue.add(request); return request; } // mWaitingRequests保存多个Request是同一个Url的情况, // 对于Request来说,同一个Url的Response也应该是相同的(request能走到这里说明request是可以缓存的), // 因此这里把这些Request缓存起来,当有一个Request有返回值了,剩下的Request也没必要再去请求网络了 // 这是Volley优化点之一。 synchronized (mWaitingRequests) { StringcacheKey= 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 = newLinkedList<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; } } }