上一篇的同步流程分析(http://www.reibang.com/p/343118d0bc19),這次來研究下異步的流程。
在這之前,先補充下纬向,Dispatcher(調(diào)度器)检诗,是保存同步和異步Call的地方胰柑,負責執(zhí)行異步AsyncCall(就是一個子線程)缭黔。
先來看看這段實現(xiàn)異步請求的最簡潔代碼:
//異步
OkHttpClient asynClient = new OkHttpClient();
Request asynRequest = new Request.Builder().url("http://......").build();
asynClient.newCall(asynRequest).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
這段代碼,前奏準備都跟同步的一樣践险,我們來看看關(guān)鍵代碼asynClient.newCall(asynRequest).enqueue(callback);
還記得嗎,上一篇里面分析過newCall捏境,會創(chuàng)建一個call接口的實現(xiàn)類RealCall對象于游,enqueue()字面上是加入隊列的意思,還是再看看call的定義吧:
public interface Call extends Cloneable {
......
Response execute() throws IOException;
void enqueue(Callback responseCallback);
......
}
不熟悉realCall的可以先去看看okhttp同步流程源碼分析(http://www.reibang.com/p/343118d0bc19)垫言,既然realCall是call的實現(xiàn)類贰剥,很好,我們?nèi)ealCall看看enqueue的實現(xiàn):
@Override public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
之前筷频,同步流程中蚌成,realCall直接調(diào)用execute(),在里面通過各種攔截器之后獲取到最終數(shù)據(jù)凛捏,然而担忧,在異步流程中,看上面最后一行代碼坯癣,入隊列的是一個AsyncCall瓶盛,成功,失敗回調(diào)的接口對象作為AsyncCall的參數(shù)示罗,在 研究client.dispatcher().enqueue():之前惩猫,我們先看看AsyncCall到底是啥:
//RealCall.java
......
final class AsyncCall extends NamedRunnable {
.....
AsyncCall(Callback responseCallback) {
super("OkHttp %s", redactedUrl());
this.responseCallback = responseCallback;
}
......
@Override protected void execute() {
boolean signalledCallback = false;
try {
Response response = getResponseWithInterceptorChain();
if (retryAndFollowUpInterceptor.isCanceled()) {
signalledCallback = true;
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
responseCallback.onResponse(RealCall.this, response);
}
} catch (IOException e) {
if (signalledCallback) {
// Do not signal the callback twice!
Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
} else {
eventListener.callFailed(RealCall.this, e);
responseCallback.onFailure(RealCall.this, e);
}
} finally {
client.dispatcher().finished(this);
}
}
}
AsyncCall是RealCall的內(nèi)部類,并且AsyncCall繼承了NamedRunnable類蚜点,這個類里面有Runable字眼轧房,execute()也是重寫父類的方法,里面的實現(xiàn)跟同步里面獲取數(shù)據(jù)是一致的绍绘,都是通過重重攔截器奶镶,最終獲取到數(shù)據(jù),只是處理起來陪拘,異步里面通過接口來回調(diào)而已厂镇。咱再看看NamedRunnable這個類:
/**
* Runnable implementation which always sets its thread name.
*/
public abstract class NamedRunnable implements Runnable {
protected final String name;
public NamedRunnable(String format, Object... args) {
this.name = Util.format(format, args);
}
@Override public final void run() {
String oldName = Thread.currentThread().getName();
Thread.currentThread().setName(name);
try {
execute();
} finally {
Thread.currentThread().setName(oldName);
}
}
protected abstract void execute();
}
NamedRunnable竟然是個抽象類,execute()抽象方法在AsyncCall實現(xiàn)左刽,在run()里面調(diào)用剪撬。我們知道,多線程的實現(xiàn)方式:實現(xiàn)Runnable接口悠反、繼承Thread類残黑,從這里,我們知道AsyncCall其實就是一個Runnable的子類斋否,可以理解為AsyncCall就是一個子線程梨水。我們再回頭來看client.dispatcher().enqueue(AsyncCall(...)):
//Dispatcher.java
public final class Dispatcher {
private int maxRequests = 64;
private int maxRequestsPerHost = 5;
......
/** 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<>();
......
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
......
}
上面已經(jīng)把關(guān)鍵代碼貼出,有兩個隊列茵臭,一個是正在運行的子線程隊列runningAsyncCalls疫诽,一個是待執(zhí)行的請求隊列readyAsyncCalls,
enqueue里面,這個判斷: 正在運行的子線程 < 64 &&單個host最大同時執(zhí)行的子線程 < 5,就把call添加到runningAsyncCalls隊列中奇徒,并且通過線程池來執(zhí)行這個call雏亚,否則就添加到readyAsyncCalls隊列。
可以摩钙,這很異步罢低,線程池都出來了,看看這個線程池:
//Dispatcher.java
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
上面我們知道正在執(zhí)行的AsyncCall會添加到runningAsyncCalls隊列胖笛,那子線程任務(wù)執(zhí)行完了后總要移除吧网持,我們回到上面的AsyncCall內(nèi)部的execute()方法,看最后面那幾行长踊,finally里面的client.dispatcher().finished(this)功舀,this就是當前的AsyncCall對象:
Dispatcher.java
/** Used by {@code Call#execute} to signal completion. */
void finished(RealCall call) {
finished(runningSyncCalls, call, false);
}
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();
}
}
看到了吧,calls.remove(call)身弊,這里面移除辟汰,這個判斷,如果是同步的話阱佛,就直接拋出異常帖汞,同步流程中,并沒有加入隊列的操作瘫絮,只有異步的時候才會執(zhí)行后續(xù)的操作涨冀。
看來要好好分析下攔截器了填硕,主要的獲取數(shù)據(jù)的操作全特么在這里面麦萤。