1. 程式人生 > >OKHttp 3.10原始碼解析(一):執行緒池和任務佇列

OKHttp 3.10原始碼解析(一):執行緒池和任務佇列

OKhttp是Android端最火熱的網路請求框架之一,它以高效的優點贏得了廣大開發者的喜愛,下面是OKhttp的主要特點:

1.支援HTTPS/HTTP2/WebSocket

2.內部維護執行緒池佇列,提高併發訪問的效率

3.內部維護連線池,支援多路複用,減少連線建立開銷

4.透明的GZIP處理降低了下載資料的大小

5.提供攔截器鏈(InterceptorChain),實現request與response的分層處理

其中OKhttp高效的原因之一是裡面使用了執行緒池,使用執行緒池可以有效減少多執行緒操作的效能開銷,提高請求效率,本篇文章從OKhttp的執行緒池開始,讓我們去探究OKhttp框架的執行機制。先讓我們來看一個OKhttp的使用例子:

        //同步請求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
        .url("http://myproject.com/helloworld.txt")
        .build();
        Response response = client.newCall(request).execute();

        //非同步請求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://myproject.com/helloworld.txt")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("OkHttp", "Call Failed:" + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("OkHttp", "Call succeeded:" + response.message());
            }
        });

上面分別是一個同步請求和非同步請求,首先我們來看看newCall方法

  @Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }

可以看到其實返回的是一個RealCall例項物件,下面分別來看看同步請求呼叫的execute方法和非同步請求呼叫的enqueue方法

  //execute方法
  @Override public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    try {
      //呼叫Dispatcher類的execute方法
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } catch (IOException e) {
      eventListener.callFailed(this, e);
      throw e;
    } finally {
      client.dispatcher().finished(this);
    }
  }


  //enqueue方法
  @Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    //呼叫Dispatcher類的enqueue方法
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }

可以看到裡面都會涉及到Dispatcher類的使用,讓我們先來認識一下Dispatcher類吧,Dispatcher類其中充當了OKhttp的任務分發器作用,它管理了OKhttp的執行緒池服務和儲存請求任務的幾個佇列Deque,我們的任務下發以後均由Dispatcher來分發執行

public final class Dispatcher {
  private int maxRequests = 64;
  private int maxRequestsPerHost = 5;
  private @Nullable Runnable idleCallback;

  private @Nullable ExecutorService executorService;

  private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
  private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

  public Dispatcher(ExecutorService executorService) {
    this.executorService = executorService;
  }

  public Dispatcher() {
  }

  public synchronized ExecutorService executorService() {
    if (executorService == null) {
      executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
          new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
    }
    return executorService;
  }
 ...
}

引數說明一下:

1.readyAsyncCalls:待執行非同步任務佇列

2.runningAsyncCalls:執行中非同步任務佇列

3.runningSyncCalls:執行中同步任務佇列

4.executorService:任務佇列執行緒池

我們來看看它這個執行緒池的建立

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

可以看到OKhttp中執行緒池的特點屬性,此執行緒池的核心執行緒數為0,最大執行緒數量為Integer.MAX_VALUE,執行緒空閒時間只能活60秒, 然後用了SynchronousQueue佇列,這是一個不儲存元素的阻塞佇列, 也就是說有任務到達的時候,只要沒有空閒執行緒,就會建立一個新的執行緒來執行任務。

一. 同步請求任務

在同步請求任務中,我們先呼叫Dispatcher的execute方法

  synchronized void executed(RealCall call) {
    runningSyncCalls.add(call);
  }

實際上這裡只是把任務新增到同步請求佇列中,執行任務不在這裡,看下面

  //execute方法
  @Override public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    try {
      //呼叫Dispatcher類的execute方法
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } catch (IOException e) {
      eventListener.callFailed(this, e);
      throw e;
    } finally {
      //執行任務結束  
      client.dispatcher().finished(this);
    }
  }

直接通過呼叫getResponseWithInterceptorChain方法獲取請求結果,其實是通過OKhttp的攔截鏈策略去執行一個請求任務,關於OKhttp的攔截鏈我們這裡暫且不詳說,後面會專門開一篇部落格詳解。在任務結束以後,會呼叫Dispatcher的finished方法,傳參RealCall例項。

  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();
    }
  }

在結束的時候,會將被執行的任務從對應的佇列中移除,從而完成了整個同步請求任務。同步請求中並沒有應用到執行緒池的功能, 下面我們來看看非同步請求任務的過程:

 

二.非同步請求任務

在非同步請求中,我們會呼叫RealCall的enqueue方法

  @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));
  }

在上面中,最終會呼叫Dispatcher的enqueue方法,將callback回撥封裝成AsyncCall物件傳參進去。

  synchronized void enqueue(AsyncCall call) {
    //預設maxRequests 為60,maxRequestsPerHost為5
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
      runningAsyncCalls.add(call);
      executorService().execute(call);
    } else {
      readyAsyncCalls.add(call);
    }
  }

如果正在執行的非同步請求任務數量小於maxRequests 並且單一Host的請求數小於maxRequestsPerHost,那麼將任務加入到正在執行的任務佇列中,並且呼叫執行緒池的execute方法準備執行任務,否則將任務新增到待執行任務佇列中。非同步任務最終都會執行AsyncCall的execute方法,我們來看看

    @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);
      }
    }

同樣會通過呼叫OKhttp的攔截器鏈去執行請求任務,完成之後呼叫Dispatcher的finished方法,非同步請求的finished方法執行和同步請求的不一樣

  void finished(AsyncCall call) {
    finished(runningAsyncCalls, call, true);
  }

  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();
    }
  }

和同步請求不一樣的是,上面finished傳的引數不一樣,這裡傳遞的是正在執行的非同步任務佇列runningAsyncCalls,promoteCalls為true。所以在移除已完成任務之後,會呼叫promoteCalls方法

  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.
    }
  }

可以看到,如果待執行任務佇列中有任務的話,就會取出任務交給執行緒池去執行。

 

三.總結

從文章的分析中,我們知道OKhttp中的執行緒池主要作用於非同步任務的操作,其中出彩的地方是在任務執行結束後,不管成功與否都會呼叫Dispatcher的finished方法,通知去執行下一個任務。

下一篇我們將會分析OKhttp的攔截器鏈的實現原理!

OKHttp 3.10原始碼解析(二):攔截器鏈