okhttp異步流程源碼分析

上一篇的同步流程分析(http://www.itdecent.cn/p/343118d0bc19),這次來研究下異步的流程。
在這之前,先補充下,Dispatcher(調(diào)度器),是保存同步和異步Call的地方,負責(zé)執(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 {

            }
        });

這段代碼,前奏準(zhǔn)備都跟同步的一樣,我們來看看關(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.itdecent.cn/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就是當(dāng)前的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ù)的操作全特么在這里面。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容