`
f303153041
  • 浏览: 44850 次
社区版块
存档分类
最新评论

Volley 核心源码解析(三)

 
阅读更多
Volley 的任务调度模型

接着上一节的 RequestQueue,在Volley 初始化 RequestQueue的时候 会执行 RequestQueue 的 start()方法,在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();
        }
    }


看看NetworkDispatcher  和 CacheDispatcher 是什么东东?

NetworkDispatcher extends Thread

CacheDispatcher extends Thread


结果两个都是线程类。

再看看循环体中 往一个叫做mDispatchers[i] 的数组中赋值了若干 NetworkDispatcher,且每个NetworkDispatcher都在创建的时候 就启动了。

找到 mDispatchers的定义:
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;

mDispatchers = new NetworkDispatcher[threadPoolSize];

原来是个默认4个元素的 线程组。

看到这里我似乎想到了线程池的基本概念,没错 这就是个线程池。



看看具体的 NetworkDispatcher 是什么样的?

做过JAVA 开发的都知道 继承 thread 类一定要重写 run()方法

在NetworkDispatcher中run 方法如下:

方法太长  一段一段的来看哈

因为是要做线程池嘛,所以线程要一直工作,所以一进run方法 就是 while(true){}
了,

  Request<?> request = mQueue.take();

mQueue:mNetworkQueue

在 PriorityBlockingQueue 队列中 take 方法如下:
   public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        E result;
        try {
            while ( (result = dequeue()) == null)
                notEmpty.await();
        } finally {
            lock.unlock();
        }
        return result;
    }

意思就是加锁 -->取出一个请求->释放锁->原队列中请求减少一个

这样就保证了 使用 volley 发送请求的时候  能按照发送请求的顺序去执行。


接下来 从队列中取出请求之后,给请求设置备注,判断请求时否被取消,如果被取消就finish。

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;
                }



紧接着,执行该请求:
  // Perform the network request.
NetworkResponse networkResponse = mNetwork.performRequest(request);

后面就是对 networkResponse 的一些状态判断和解析。

Response<?> response = request.parseNetworkResponse(networkResponse);

在volley 中 解析NetworkResponse 的具体方法 交给 Request 的 子类去实现。如,ImageRequest,JsonRequest,StringRequest等

同时,缓存 这个已经执行的请求:
if (request.shouldCache() && response.cacheEntry != null) {
                    mCache.put(request.getCacheKey(), response.cacheEntry);
                    request.addMarker("network-cache-written");
                }


看到这里,我们可以得出一个结论,Volley 初始化 RequestQueue 的时候 创建了一个
默认4个大小的线程池,每个线程同步 的从PriorityBlockingQueue 类型的请求队列中拿出一个请求并执行。



接下来看看 CacheDispatcher 缓存任务调度:


    /** The queue of requests coming in for triage. */
    private final BlockingQueue<Request<?>> mCacheQueue;

    /** The queue of requests going out to the network. */
    private final BlockingQueue<Request<?>> mNetworkQueue;

与 NetworkDispatcher 不同的是 CacheDispatcher  不仅有缓存队列 还有请求队列,

同样是while (true) {  request = mCacheQueue.take();;  ...}

不停的从 mCacheQueue 拿出缓存过的请求:
// 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;
                }
这里看到 被缓存的请求时根据请求的cacheKey 从cache中取出,如果取出的缓存为空,直接把请求 放到 mNetworkQueue ,也就是说把请求交给 了 NetworkDispatcher去执行。

如果请求的缓存对象过期,同上:
  // 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;
                }
这里我们看到一个关键性的代码:
Response<?> response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));


这是什么意思呢?

  Volley不仅缓存了请求本身,而且缓存了请求的响应结果,此时做的就是从缓存中取出响应的结果,这样就不用再发请求去服务器上了。

接下来,

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.
                    final Request<?> finalRequest = request;
                    mDelivery.postResponse(request, response, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mNetworkQueue.put(finalRequest);
                            } catch (InterruptedException e) {
                                // Not much we can do about this.
                            }
                        }
                    });
                }

如果缓存数据不需要刷新,只需要用回掉接口返回值,反之,把请求放入mNetworkQueue,等待 NetworkDispatcher 执行。



至此,Volley 的 线程模型分析告一段落,我们看到了线程组 NetworkDispatcher[] 和 单线程 CacheDispatcher 通过 两个  BlockingQueue 巧妙地实现了网络请求任务的交替轮换。



下一节  Volley的缓存 http://f303153041.iteye.com/blog/2281360
















分享到:
评论

相关推荐

    Volley源码解析

    Volley源码解析,个人的理解与注释

    volley源码和jar包

    这是volley的源码以及jar包,用于小数据量的频繁的网络请求。

    Volley框架源码

    关于Volley框架的源码,及一些关于开发的一些例子讲解

    android-volley源码

    android-volley源码代码 android Volley ---------- This is an unofficial mirror for [android volley library](https://android.googlesource.com/platform/frameworks/volley), the source code will ...

    Volley源码+包

    Volley源码+包:在开发android使用第三方框架有两种方法:一是直接加框架的源码,二是在libs中加jar包。

    volley源码

    volley源码,有兴趣的同学可以下载研究一下。 谷歌建议使用volley框架进行网络请求。

    volley联网解析网络上的xml文件

    采用volley的联网方式,实现解析服务端返回的xml数据

    google官方最新volley源码

    google官方最新volley源码,如果你想对volley有更深的认识就下来学习吧

    Volley源码与jar包

    Volley是2013年Google I/O上发布的,它是Android平台上的网络通信库,对常用的网络通信功能作了封装,能使网络通信更快, 更简单,更健壮。以前使用网络通信一般都是用AsyncTaskLoader、HttpURLConnection、...

    android volley源码

    android volley源码,从google下载的volley源码,方便理解和使用

    Github-volley jar包和源码

    volley是一个优秀的安卓开源网络访问工具 这里包含一个volley代码jar和源码,版本是2015.03.03的1.0.11版本 更多资料可以参见volley的github地址: https://github.com/mcxiaoke/android-volley

    Volley源码

    Volley源码,相关博文:http://www.cnblogs.com/tianzhijiexian/p/4255488.html

    Android Volley源码20160414版

    Android Volley源代码,更新日期20160414

    可查看Volley源码

    volley作为库文件 这个demo ,可以查看volley源码

    volley的demo(包括volley源码)

    一共两个demo: 1.使用volley.jar进行开发的demo 2.将volley源码添加到工程中,进行演示的demo。最重要的是在源码中添加了很多中文注释。

    volley框架源码实例

    volley框架的实例源码,包含二次封装,可下载导入工程项目运行

    Volley源码及文档

    Volley源码和文档,本人验证无误,遂上传,希望对你有帮助~

    Volley.jar及源码

    1.0.19版本的Volley.jar和Volley源码。截止于2015.09.08。更多详情见github:https://github.com/mcxiaoke/android-volley

Global site tag (gtag.js) - Google Analytics