当前位置: 代码迷 >> Android >> Volley实现的疑点
  详细解决方案

Volley实现的疑点

热度:83   发布时间:2016-04-27 22:13:06.0
Volley实现的疑问
最近在看Volley的源码,我发现在执行Volley.newRequestQueue初始化的时候,也就是启动了几个线程,默认是1个CacheDispatcher和4个NetworkDispatcher,也就是启动了5个线程,1个用来缓存,4个用来网络请求,完后将网络请求Request放入networkQueue或者cacheQueue队列,通过CacheDispatcher和NetworkDispatcher来从队列中读和取Request进行处理,我的疑问是,就我看到的源码,1个CacheDispatcher和4个NetworkDispatcher并没有用线程池管理起来,而就简单的继承了Thread方法,为什么Volley不用线程池呢,请熟悉Volley的人解答下
------解决思路----------------------
线程池是对一些不用的thread进行回收和管理,但是这里只有五个固定的线程,不需要回收,因此不需要
------解决思路----------------------
引用:
Quote: 引用:

线程池是对一些不用的thread进行回收和管理,但是这里只有五个固定的线程,不需要回收,因此不需要


恩,有道理,还有个小问题我懒得再开一贴了,也是Volley的


if (!entry.refreshNeeded()) { //如果请求有效且并不需要刷新,则丢进Delivery中处理,最终会触发如StringRequest这样的请求子类的onResponse或onErrorResponse  
                // 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.  
                        }  
                    }  
                });  
            }  

这是CacheDispatcher中的一段代码,意思是如果之前有缓存且缓存不需要刷新,则直接返回给用户,否则,还是返回给用户,完后将这个请求加入mNetworkQueue队列,我的问题是,在需要刷新的情况下,还把之前的缓存返回给用户干什么呢,直接请求最新的不好吗,现在是先把缓存返回过去,完后又加入mNetworkQueue队列,那不是请求完成后又返回一次,用户接到2次返回,一次缓存的,一次新的,感觉很奇怪

这个只是实现策略,你说的那段代码是在 缓存的新鲜期以内,还没有过期,但是即将过期(sttl),所以先显示,然后更新该缓存数据。