mCacheQueue:缓存队列
mNetworkQueue:网络请求队列
这两个队列都是线程安全阻塞的,类型为PriorityBlockingQueue,读不到请求就会阻塞等待。
CacheDispatcher线程:处理缓存队列里面的请求
NetworkDispatcher线程:处理网络请求队列里面的请求
取消策略:
构造Request对象放入请求队列之后,这个对象你还是可以重设属性的,调用request.cancel();会设置mCanceled标志位为true,在做网络请求的时候CacheDispatcher 和 NetworkDispatcher线程会skip掉这个请求。
LRU缓存策略
使用LinkedHashMap实现默认的LRU缓存策略,后续解答
重试策略:
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.volley;
/**
* Default retry policy for requests.
*/
public class DefaultRetryPolicy implements RetryPolicy {
//已超时时间
private int mCurrentTimeoutMs;
//已经重试次数
private int mCurrentRetryCount;
//最大重试次数
private final int mMaxNumRetries;
//对于请求失败之后的请求,并不会隔相同的时间去请求Server,不会以线性的时间增长去请求,
//而是一个曲线增长,一次比一次长,如果backoff因子是2,当前超时为3,即下次再请求隔6S。
private final float mBackoffMultiplier;
//默认超时时间5s
public static final int DEFAULT_TIMEOUT_MS = 5000;
//默认重试次数2次
public static final int DEFAULT_MAX_RETRIES = 2;
//默认增长因子1.2
public static final float DEFAULT_BACKOFF_MULT = 1.2f;
//构造默认的DefaultRetryPolicy对象
public DefaultRetryPolicy() {
this(DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT);
}
//构造自定义的DefaultRetryPolicy对象
public DefaultRetryPolicy(int initialTimeoutMs, int maxNumRetries, float backoffMultiplier) {
mCurrentTimeoutMs = initialTimeoutMs;
mMaxNumRetries = maxNumRetries;
mBackoffMultiplier = backoffMultiplier;
}
//得到已超时时间
@Override
public int getCurrentTimeout() {
return mCurrentTimeoutMs;
}
//得到已重试次数
@Override
public int getCurrentRetryCount() {
return mCurrentRetryCount;
}
//判断是否需要重试处理
@Override
public void retry(VolleyError error) throws VolleyError {
//重试字数替曾
mCurrentRetryCount++;
//计算新的重试时间,计算方式 y = x + x*k k是常量
mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);
//是否需要重试:如果不需要则抛出一个没有捕获的异常,包括AuthFailureError、TimeoutError等
if (!hasAttemptRemaining()) {
throw error;
}
}
//判断是够超过重试次数
protected boolean hasAttemptRemaining() {
return mCurrentRetryCount <= mMaxNumRetries;
}
}
这个类的只是判断需不需要重试,已经调整重试参数,没有做具体的逻辑操作。真正的重试操作是在BasicNetwork中的performRequest函数里面处理的。