簡要分析Volley響應3次的原理

Volley是個輕量級的通訊框架,對Android開發來講確實比較好用,擴展性也強。不過今天談的不是它的應用,而是剖析它的一個問題,就是Volley使用緩存,則會響應3次。這篇文章的思路只講最核心的代碼,其餘代碼就不貼了,獲取源碼也簡單的。
java

在Volley中有一個緩存線程,4個網絡請求線程,分別爲CacheDispatcher.java,NetworkDispatcher.java。json

分析過程不按照調用順序來說,是從最重要的地方開始,而後再分析調用它的地方,這樣帶着問題來分析,可能更有意思。緩存

CacheDispatcher.java的run方法中,有以下代碼:網絡

  while (true) {
            try {
                // Get a request from the cache triage queue, blocking until
                // at least one is available.
                final Request<?> request = mCacheQueue.take();
                request.addMarker("cache-queue-take");

                // If the request has been canceled, don't bother dispatching it.
                if (request.isCanceled()) {
                    request.finish("cache-discard-canceled");
                    continue;
                }

                // Attempt to retrieve this item from cache.
 1               Cache.Entry entry = mCache.get(request.getCacheKey());
 2               if (entry == null) {
                    request.addMarker("cache-miss");
                    // Cache miss; send off to the network dispatcher.
 3                  mNetworkQueue.put(request);
                    continue;
                }

                //=======修改判斷有緩存就解析取緩存數據=屏蔽判斷緩存過時和服務端驗證緩存是否須要刷新 ==============
                // We have a cache hit; parse its data for delivery back to the request.
                request.addMarker("cache-hit");
                Response<?> response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));
                request.addMarker("cache-hit-parsed");
                
                request.addMarker("cache-hit-refresh-needed");
                request.setCacheEntry(entry);

                // Mark the response as intermediate.
                response.intermediate = true;

                // Post the intermediate response back to the user and have
                // the delivery then forward the request along to the network.
4                mDelivery.postResponse(request, response, new Runnable() {
                    @Override
                    public void run() {
                        try {
5                           mNetworkQueue.put(request);
                        } catch (InterruptedException e) {
                            // Not much we can do about this.
                        }
                    }
                });
                
6                mDelivery.postResponse(request, response);

有while(true),說明這個線程是一直運行着,在1處,從request中取出key對應的緩存Entry,key其實就是request的url,2處若是緩存爲空,3處在將請求加入網絡請求隊列,continue,繼續下一次循環(由NetworkDispatcher.java會處理這個請求)。這種狀況不在討論以內,在4處,mDelivery調用postResponse,看看裏面怎麼寫的。mDelivery是ExecutorDelivery的實例。app

 @Override
    public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
        request.markDelivered();
        request.addMarker("post-response");
1        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
    }

在1處,則看看mResponsePoster的定義。框架

  public ExecutorDelivery(final Handler handler) {
        // Make an Executor that just wraps the handler.
        mResponsePoster = new Executor() {
            @Override
            public void execute(Runnable command) {
                handler.post(command);
            }
        };
    }

能夠看到mResponsePoster所要執行的任務,執行hanlder.post(commnad)後,任務是在主線程執行的,看看command的實現代碼,挑它的run方法看
ide

  public void run() {
            // If this request has canceled, finish it and don't deliver.
            if (mRequest.isCanceled()) {
                mRequest.finish("canceled-at-delivery");
                return;
            }

            // Deliver a normal response or error, depending.
            if (mResponse.isSuccess()) {
1                mRequest.deliverResponse(mResponse.result);
            } else {
2                mRequest.deliverError(mResponse.error);
            }

            // If this is an intermediate response, add a marker, otherwise we're done
            // and the request can be finished.
            if (mResponse.intermediate) {
                mRequest.addMarker("intermediate-response");
            } else {
3                mRequest.finish("done");
            }

            // If we have been provided a post-delivery runnable, run it.
            if (mRunnable != null) {
                mRunnable.run();
            }
       }

1處就是將結果返回,看看deliverResponse()的實現,繼承Requst的類JsonRequest,看它的實現:post

 protected void deliverResponse(T response) {
   1     mListener.onResponse(response);
    }

1處這個mListener的類型是Response.Listener,正好是咱們定義request的時候傳進去的,如ui

request = new JsonPostRequest(IMConfig.mUserSummary, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject jsonObject) {

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        
    }
}, map);

這樣流程完畢,就是響應了1次,第二次是怎麼來的呢,回顧CacheDispatcher.java的5處,是將請求放到了網絡請求隊列中,網絡線程NetworkDispatcher.java就會檢測到這個請求,會執行網絡操做,操做完成後,也會回到主線程響應,簡要分析它的代碼 run方法,以下this

        while (true) {
            try {
                // Take a request from the queue.
                request = mQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }

            try {
                request.addMarker("network-queue-take");

                // If the request was cancelled already, do not perform the
                // network request.
                if (request.isCanceled()) {
                    request.finish("network-discard-cancelled");
                    continue;
                }

                addTrafficStatsTag(request);

                // Perform the network request.
                NetworkResponse networkResponse = mNetwork.performRequest(request);
                request.addMarker("network-http-complete");

                // If the server returned 304 AND we delivered a response already,
                // we're done -- don't deliver a second identical response.
                if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                    request.finish("not-modified");
                    continue;
                }

                // Parse the response here on the worker thread.
                Response<?> response = request.parseNetworkResponse(networkResponse);
                request.addMarker("network-parse-complete");

                // Write to cache if applicable.
                // TODO: Only update cache metadata instead of entire record for 304s.
                if (request.shouldCache() && response.cacheEntry != null) {
1                   mCache.put(request.getCacheKey(), response.cacheEntry);
                    request.addMarker("network-cache-written");
                }

                // Post the response back.
                request.markDelivered();
2               mDelivery.postResponse(request, response);
            } catch (VolleyError volleyError) {
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                mDelivery.postError(request, new VolleyError(e));
            }
        }

能夠看到又是個死循環,從而網絡隊列裏只要有request,必定會被執行到,其餘地方不看,就看2處,經過前面的分析,清楚postResponse的邏輯是將結果返回到主線程響應,這就是第二次。第三次就看CacheDispatcher.java的run方法的6處,又發現調用了一次postResponse(),又將結果返回到主線程響應,到這裏共有3次響應了,至於google的這個volley爲何要作3次,也以爲困惑,我的以爲第三次響應是不必的。前面的分析有不少細節之處沒有分析到位,就如同前面所說,只取這個問題的最核心的地方,其餘細節之處能夠看源碼。


在最新的Volley的版本中,已把這個問題修復了,CacheDispatcher.java代碼以下:

 while (true) {
            try {
                // Get a request from the cache triage queue, blocking until
                // at least one is available.
                final Request<?> request = mCacheQueue.take();
                request.addMarker("cache-queue-take");

                // If the request has been canceled, don't bother dispatching it.
                if (request.isCanceled()) {
                    request.finish("cache-discard-canceled");
                    continue;
                }

                // Attempt to retrieve this item from cache.
                Cache.Entry entry = mCache.get(request.getCacheKey());
                if (entry == null) {
                    request.addMarker("cache-miss");
                    // Cache miss; send off to the network dispatcher.
                    mNetworkQueue.put(request);
                    continue;
                }

                // If it is completely expired, just send it to the network.
                if (entry.isExpired()) {
                    request.addMarker("cache-hit-expired");
                    request.setCacheEntry(entry);
                    mNetworkQueue.put(request);
                    continue;
                }

                // We have a cache hit; parse its data for delivery back to the request.
                request.addMarker("cache-hit");
                Response<?> response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));
                request.addMarker("cache-hit-parsed");

 1               if (!entry.refreshNeeded()) {
                    // Completely unexpired cache hit. Just deliver the response.
                    mDelivery.postResponse(request, response);
                } else {
                    // Soft-expired cache hit. We can deliver the cached response,
                    // but we need to also send the request to the network for
                    // refreshing.
                    request.addMarker("cache-hit-refresh-needed");
                    request.setCacheEntry(entry);

                    // Mark the response as intermediate.
                    response.intermediate = true;

                    // Post the intermediate response back to the user and have
                    // the delivery then forward the request along to the network.
                    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;
            }
        }

看1處的代碼,經過對實體判斷須要更新的話,會再次請求網絡,不更新的話,則直接響應。

相關文章
相關標籤/搜索