在閱讀源碼之前,我們先大致了解一下Volley運行的一些基本原理:Volley在啟動之后會啟動兩種線程僚害,分別是緩存調(diào)度線程和網(wǎng)絡請求線程,默認情況下會創(chuàng)建4個網(wǎng)絡請求線程組成線程池亚隙。Volley的請求隊列宾抓,無論是準備就緒的網(wǎng)絡請求隊列還是緩存隊列,都是采用優(yōu)先級隊列PriorityBlockingQueue進行存儲的树叽,所以Volley的網(wǎng)絡請求是具有優(yōu)先級控制功能的舆蝴;由于Volley具有緩存調(diào)度,所以Volley是可以過濾重復的網(wǎng)絡請求题诵。我們可以在Volley的請求回調(diào)方法中安全的操作主線程洁仗,不需要擔心Volley子線程引起的跨線程UI更新問題,這歸功于Volley結果分發(fā)器為我們做了跨線程處理性锭。
如果上面對Volley的原理簡單介紹無法理解赠潦,不要緊,下來我們將圍繞Volley的網(wǎng)絡請求線程調(diào)度草冈、緩存機制她奥、優(yōu)先級控制瓮增、結果分發(fā)器展開解析。
我們使用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方法的第一行就是創(chuàng)建一個文件目錄(文件夾)凡资,這個目錄將用于緩存Volley的網(wǎng)絡請求砸捏。接著,會根據(jù)系統(tǒng)的版本隙赁,分別創(chuàng)建HurlStack和HttpClientStack带膜。這兩個類就是Volley的網(wǎng)絡請求類,它們將執(zhí)行真正的網(wǎng)絡請求操作鸳谜。只不過膝藕,HurlStack底層調(diào)用的是HttpUrlConnection類來實現(xiàn)網(wǎng)絡請求,而HttpClientStack是調(diào)用HttpClient類來實現(xiàn)網(wǎng)絡請求咐扭,因為在API9以下芭挽,HttpUrlConnection類是存在Bug的,所以Volley在此做了兼容蝗肪。我們之后對網(wǎng)絡請求的分析將基于HurlStack類來展開袜爪。
2、接著創(chuàng)建BasicNetwork類薛闪,BasicNetwork實現(xiàn)了Network接口辛馆,它將負責把HurlStack類執(zhí)行網(wǎng)絡請求后的結果進一步加工處理。
3豁延、最后創(chuàng)建RequestQueue類昙篙,并啟動它。RequestQueue就是網(wǎng)絡請求隊列诱咏、緩存的集成中心苔可,網(wǎng)絡請求線程、緩存線程就是由他的start方法創(chuàng)建啟動的袋狞。
由此焚辅,我們定位到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方法里面,先調(diào)用程序清除mCacheDispatcher和mDispatchers苟鸯,接著在重新new創(chuàng)建新的mCacheDispatcher和mDispatchers同蜻。
那么mCacheDispatcher和mDispatchers是什么呢?
mCacheDispatcher是CacheDispatcher類早处,繼承于Thread湾蔓,它就是前面所說的緩存調(diào)度線程,在其run方法中進入死循環(huán)陕赃,不斷的讀取處理具有優(yōu)先級性質(zhì)的緩存隊列中的請求卵蛉。
mDispatchers也是NetworkDispatcher類颁股,繼承于Thread類,它就是網(wǎng)絡請求調(diào)度線程傻丝,由mDispatchers.length個NetworkDispatcher組成網(wǎng)絡請求調(diào)度線程池甘有。
到這里,我們知道網(wǎng)絡請求被壓進請求隊列和緩存隊列葡缰,通過網(wǎng)絡請求調(diào)度線程和緩存調(diào)度線程來處理他們亏掀,最終通過分發(fā)器回調(diào)到UI界面。那么泛释,這些請求是怎么被壓進隊列里面的呢滤愕?回想一下,我們使用Volley的時候怜校,除了創(chuàng)建RequestQueue之外间影,我們在進行網(wǎng)絡請求的時候,會把創(chuàng)建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;
}
}
由于網(wǎng)絡調(diào)度線程池是由默認4個(mDispatchers.length)Thread的網(wǎng)絡調(diào)度器組成的,所以這里用synchronized修飾同步塊(第9行代碼)裙顽,把Request添加到當前隊mCurrentRequests列里面付燥。接著判斷Request是否緩存的標志,若不需要緩存直接add到網(wǎng)絡請求就緒隊列mNetworkQueue里面直接準備進行網(wǎng)絡請求操作愈犹;如果允許緩存键科,則會到阻塞隊列mWaitingRequests里面查找是否存在,存在的話漩怎,刷新阻塞隊列里面對應的Request勋颖;不存在的話,則把Request put進阻塞隊列和緩存隊列mCacheQueue扬卷。
那么阻塞隊列mWaitingRequests是起什么作用的呢牙言?緩存隊列mCacheQueue會由CacheDispatcher去調(diào)度,“備份”一份在阻塞隊列中怪得,為何呢?回到阻塞隊列聲明的地方:
/**
* 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請求發(fā)起,后續(xù)的相同的Request并不會產(chǎn)生新的Request欢伏,而是更新原來的第一個的Request信息入挣。