本章我们介绍OkHttp的任务调度器Dispatcher,dispatcher的作用为维护请求的状态,并维护一个线程池。Dispatcher包含了三个队列和一个线程池,看注释大家应该能明白他们是做什么的
/** Executes calls. Created lazily. */ private @Nullable ExecutorService executorService; /** Ready async calls in the order they'll be run. */ private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */ private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>(); /** Running synchronous calls. Includes canceled calls that haven't finished yet. */ private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();同步请求只有一个队列,在执行executed方法时把网络请求call放入runningSyncCalls队列
synchronized void executed(RealCall call) { runningSyncCalls.add(call); }
异步请求执行的是dispatcher的enqueue方法,异步请求为什么需要两个队列?这里其实是一个生产者消费者模型
Dispatcher 生产者
ExecutorService 消费者池
因此,一个生产者消费者模型需要对应两个队列,一个是正在执行的请求队列,一个是等待执行的请求队列。
下面这张图描述了异步请求的过程,每当一个请求入队时,首先会判断正在执行的队列是否已满,没满则放入线程池执行,否则将call放入就绪等待队列
synchronized void enqueue(AsyncCall call) { if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) { runningAsyncCalls.add(call); executorService().execute(call); } else { readyAsyncCalls.add(call); } }
同时我们之前提到,AsyncCall在execute方法执行完后,会调用dispatcher的finished方法,这里会调用promoteCalls方法
private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) { int runningCallsCount; Runnable idleCallback; synchronized (this) { if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!"); if (promoteCalls) promoteCalls(); runningCallsCount = runningCallsCount(); idleCallback = this.idleCallback; } if (runningCallsCount == 0 && idleCallback != null) { idleCallback.run(); } }
对等待队列和正在执行的队列进行管理,这边会根据具体条件把ready队列的放入running队列等待执行,注释其实写的非常清楚了
private void promoteCalls() { if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity. if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote. for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) { AsyncCall call = i.next(); if (runningCallsForHost(call) < maxRequestsPerHost) { i.remove(); runningAsyncCalls.add(call); executorService().execute(call); } if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity. } }
总结
不论是同步还是异步请求,封装好的Call都会在dispatcher里被调度执行,这里我们要理解dispatcher里的三个队列和执行线程池,以及dispatcher是如何对队列进行操作的。