Volley源碼解析(一)——主流程分析

在閱讀源碼之前,我們先大致了解一下Volley運行的一些基本原理:Volley在啟動之后會啟動兩種線程,分別是緩存調(diào)度線程和網(wǎng)絡(luò)請求線程,默認情況下會創(chuàng)建4個網(wǎng)絡(luò)請求線程組成線程池。Volley的請求隊列,無論是準備就緒的網(wǎng)絡(luò)請求隊列還是緩存隊列,都是采用優(yōu)先級隊列PriorityBlockingQueue進行存儲的,所以Volley的網(wǎng)絡(luò)請求是具有優(yōu)先級控制功能的;由于Volley具有緩存調(diào)度,所以Volley是可以過濾重復(fù)的網(wǎng)絡(luò)請求。我們可以在Volley的請求回調(diào)方法中安全的操作主線程,不需要擔心Volley子線程引起的跨線程UI更新問題,這歸功于Volley結(jié)果分發(fā)器為我們做了跨線程處理。
如果上面對Volley的原理簡單介紹無法理解,不要緊,下來我們將圍繞Volley的網(wǎng)絡(luò)請求線程調(diào)度、緩存機制、優(yōu)先級控制、結(jié)果分發(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)絡(luò)請求。接著,會根據(jù)系統(tǒng)的版本,分別創(chuàng)建HurlStack和HttpClientStack。這兩個類就是Volley的網(wǎng)絡(luò)請求類,它們將執(zhí)行真正的網(wǎng)絡(luò)請求操作。只不過,HurlStack底層調(diào)用的是HttpUrlConnection類來實現(xiàn)網(wǎng)絡(luò)請求,而HttpClientStack是調(diào)用HttpClient類來實現(xiàn)網(wǎng)絡(luò)請求,因為在API9以下,HttpUrlConnection類是存在Bug的,所以Volley在此做了兼容。我們之后對網(wǎng)絡(luò)請求的分析將基于HurlStack類來展開。
2、接著創(chuàng)建BasicNetwork類,BasicNetwork實現(xiàn)了Network接口,它將負責(zé)把HurlStack類執(zhí)行網(wǎng)絡(luò)請求后的結(jié)果進一步加工處理。
3、最后創(chuàng)建RequestQueue類,并啟動它。RequestQueue就是網(wǎng)絡(luò)請求隊列、緩存的集成中心,網(wǎng)絡(luò)請求線程、緩存線程就是由他的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)絡(luò)請求調(diào)度線程,由mDispatchers.length個NetworkDispatcher組成網(wǎng)絡(luò)請求調(diào)度線程池。
到這里,我們知道網(wǎng)絡(luò)請求被壓進請求隊列和緩存隊列,通過網(wǎng)絡(luò)請求調(diào)度線程和緩存調(diào)度線程來處理他們,最終通過分發(fā)器回調(diào)到UI界面。那么,這些請求是怎么被壓進隊列里面的呢?回想一下,我們使用Volley的時候,除了創(chuàng)建RequestQueue之外,我們在進行網(wǎng)絡(luò)請求的時候,會把創(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)絡(luò)調(diào)度線程池是由默認4個(mDispatchers.length)Thread的網(wǎng)絡(luò)調(diào)度器組成的,所以這里用synchronized修飾同步塊(第9行代碼),把Request添加到當前隊mCurrentRequests列里面。接著判斷Request是否緩存的標志,若不需要緩存直接add到網(wǎng)絡(luò)請求就緒隊列mNetworkQueue里面直接準備進行網(wǎng)絡(luò)請求操作;如果允許緩存,則會到阻塞隊列mWaitingRequests里面查找是否存在,存在的話,刷新阻塞隊列里面對應(yīng)的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<?>>>();

從他的英文注釋中可以知道,這個阻塞隊列是為了防止重復(fù)的Request。當有多個相同的Request請求發(fā)起,后續(xù)的相同的Request并不會產(chǎn)生新的Request,而是更新原來的第一個的Request信息。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容