OKHttp 3.10源码解析(一):线程池和任务队列

版权声明:本文为博主石月的原创文章,转载请注明出处 https://blog.csdn.net/liuxingrong666/article/details/84957103

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源码解析(二):拦截器链

 

猜你喜欢

转载自blog.csdn.net/liuxingrong666/article/details/84957103