OkHttp3 有两种运行方式:

1.同步阻塞调用并且直接返回;

2.通过内部线程池分发调度实现非阻塞的异步回调;

下面讲的是非阻塞异步回调,OkHttp在多并发网络下的分发调度过程,主要是Dispatcher对象:

多线程:多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。但如果对多线程应用不当,会增加对单个任务的处理时间

ThreadPool线程池:线程池的关键在于线程复用以减少非核心任务的损耗。

T = T1+T2+T3其中T1和T3是多线程本身的带来的开销(在Java中,通过映射pThead,并进一步通过SystemCall实现native线程),我们渴望减少T1,T3所用的时间,从而减少T的时间。但一些线程的使用者并没有注意到这一点,所以在程序中频繁的创建或销毁线程,这导致T1和T3在T中占有相当比例。显然这是突出了线程的弱点(T1,T3),而不是优点(并发性)。

线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。

1.通过对线程进行缓存,减少了创建销毁的时间损失;

2.通过控制线程数量阀值,减少了当线程过少时带来的CPU闲置(比如说长时间卡在I/O上了)与线程过多时对JVM的内存与线程切换时系统调用的压力.

构造单例线程池:

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;
}
参数说明:
  • int corePoolSize: 最小并发线程数,这里并发同时包括空闲与活动的线程,如果是0的话,空闲一段时间后所有线程将全部被销毁。
  • int maximumPoolSize: 最大线程数,当任务进来时可以扩充的线程最大值,当大于了这个值就会根据丢弃处理机制来处理
  • long keepAliveTime: 当线程数大于corePoolSize时,多余的空闲线程的最大存活时间,类似于HTTP中的Keep-alive
  • TimeUnit unit: 时间单位,一般用秒
  • BlockingQueue<Runnable> workQueue: 工作队列,先进先出,可以看出并不像Picasso那样设置优先队列。(阻塞队列)
  • ThreadFactory threadFactory: 单个线程的工厂,可以打Log,设置Daemon(即当JVM退出时,线程自动结束)等。
可以看出,在Okhttp中,构建了一个阀值为[0, Integer.MAX_VALUE]的线程池,它不保留任何最小线程数,随时创建更多的线程数,当线程空闲时只能活60秒,它使用了一个不存储元素的阻塞工作队列,一个叫做"OkHttp Dispatcher"的线程工厂。
也就是说,在实际运行中,当收到10个并发请求时,线程池会创建十个线程,当工作完成后,线程池会在60s后相继关闭所有线程。
 aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlAAAABkCAIAAADG9JmAAAAa1ElEQVR4nO1dO67cSLKdVbxt1FK4ira5gDZktE9AVmsDckRDdgPyBRAQtIFBA92LmHKfQTIZ/4xkFVn3iuegMNOXZP4iI+JEBEuV/7kDAAAAwAXwn1dPAAAAAADOAAgPAAAAuARAeAAAAMAlAMIDAAAALgEQHgAAAHAJgPAAAACASwCEBwAAAFwCIDwAAADgEgDhRfgf8Ay8ehsBAADu9zzhjf2tG6ZDp3IGxv5268f6tfsdbPdUOPsxDZ0t/GehRW89RaCYho4+I7sfe9WDaCEekXfbVLQRY+/J4kkDPI76RFrlo1RsFfk0dLfb7aZbLjca/J3WMr2vwJtAjvCmoavuf9EfjsZdP9YDWu7PdomvJohfENaGvCHCy+j4/T6NfUfUmnY/9rfb7dYPk/J8vFs2JeUY8yq63JG+XIA0nOduSvt5hDdLIUA7nckHGuRjdeht9CY8saUKy/1t78oE9H+YEwogW7Wtl5J55ZFmVHfW2OYm/TRHfHaa5RGeQ1/BJlm+axq6xikf5gH1dpUtsW68mh1+QZyz3cIZBL6wXcVpS+nXPE9tuEDqjaj7aVTR+/0+TSOzMCObFKt3fMhzCc/tqe5so+bt8qEEwITUDQNrxCMQSngx2yx/zP9H7gRqV2HnDOEtS9ZyclS6G6ZN9E/OPUMLbtdPhjMJjyDplOzHWj3akYRHg13DENbHQHjHIE8xjyi5RXiec+PbvmfUagLJGJFlDrOSC8JrUVHjb+NWLj14aYZHB9/+W0+pWT7UyfeDUD5nuW2E51zTQmAc2aL7PKQKWxFd0hneMYSnhG+gUT9Fy/MJT8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LjZTVWTSbQQG9BwHVxJOGlNKw1w3OmoVlw6LqusJx4knxrbVr+q5IPWdfj9TmE52cP+k6wYNu2yfTk5DKEJyiPPkHkS0XtPHLfAhlJn+xStYmeXDPhTUv+byuat9ECLYTnhEBbhsk0VXh1ToqG8FxkCc+4rgKdO1cwKk4qCT8jM3aWRhush5vdiN2i2szsRIY2ZjKr5gBcFgcSXi6iiglP3HI4YRuP2dj2T6MS8855ifx7FbX6iVVQ2UVmvWIW9uQD2ndSjRzhkTFltkWnSryv4u7thgpCrLJSpYmaWnuGtw10DuE53VnjEyWxhBXEOet/1FeaVGVJ1f67MM4hDuGJHi2tnzsbNC2VJlv/wpq40mjp2ItCPRNwCa8aUFLYriBHDuop105CtiOPrAmb8s3h/PVzxlBV0me9KNtTGZ8ehRURI49kTmN1bkaskfTsbxl5wrNwCuH5CMM/sjInliDZ7zRNhPCm8r0smRs9qMoA8AviuNMS8slQtruUs5uHnfS/OaqwpRsWc/fxpCUF5D32XT/uHGQq7yfNZAKEdzrhOblIE1jyt8U9ortNOueqMgC8I7yZ44EAAAAA4EiA8AAAAIBLAIQHAAAAXAIgPAAAAOASAOEBAAAAlwAIDwAAALgEQHgAAADAJQDCAwAAAC4BEB4AAABwCYDwAAAAgEsAhAcAAABcAiA8AAAA4BIA4QEAAACXAAgPAAAAuARAeAAAAMAlAMIDAAAALgEQHgAAAHAJgPAAAACASwCEBwAAAFwCIDwAAADgEgDhAQAAAJfA/wMZrNUZpG8RtAAAAABJRU5ErkJggg==" alt="" />反向代理模型: 在OkHttp中,使用了与Nginx类似的反向代理与分发技术,这是典型的单生产者多消费者问题。我们知道在Nginx中,用户通过HTTP(Socket)访问前置的服务器,服务器会添加Header并自动转发请求给后端集群,接着返回数据结果给用户(比如简书上次挂了也显示了Nginx报错)。通过将工作分配给多个后台服务器并共享Session,可以提高服务的负载均衡能力,实现非阻塞、高可用、高并发连接,避免资源全部放到一台服务器而带来的负载,速度,在线率等影响。
作为任务的派发器,线程池对应多台后置服务器,用AsyncCall对应Socket请求,用Deque<readyAsyncCalls>对应Nginx的内部缓存
具体成员如下
  • maxRequests = 64: 最大并发请求数为64
  • maxRequestsPerHost = 5: 每个主机最大请求数为5
  • Dispatcher: 分发者,也就是生产者(默认在主线程)
  • AsyncCall: 队列中需要处理的Runnable(包装了异步回调接口)
  • ExecutorService:消费者池(也就是线程池)
  • Deque<readyAsyncCalls>:缓存(用数组实现,可自动扩容,无大小限制)
  • Deque<runningAsyncCalls>:正在运行的任务,仅仅是用来引用正在运行的任务以判断并发量,注意它并不是消费者缓存
通过将请求任务分发给多个线程,可以显著的减少I/O等待时间

OkHttp的任务调度

当我们希望使用OkHttp的异步请求时,一般进行如下构造:
当HttpClient的请求入队时,根据代码,我们可以发现实际上是Dispatcher进行了入队操作
synchronized void enqueue(AsyncCall call) {
 if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
//添加正在运行的请求
 runningAsyncCalls.add(call);
 //线程池执行请求
  executorService().execute(call);
} else {
//添加到缓存队列排队等待
readyAsyncCalls.add(call);
}
}
可以发现请求是否进入缓存的条件如下:(runningRequests<64 && runningRequestsPerHost<5)如果满足条件,那么就直接把AsyncCall直接加到runningCalls的队列中,并在线程池中执行(线程池会根据当前负载自动创建,销毁,缓存相应的线程)。反之就放入readyAsyncCalls进行缓存等待。

我们再分析请求元素AsyncCall(它实现了Runnable接口),它内部实现的execute方法如下:

当任务执行完成后,无论是否有异常,finally代码段总会被执行,也就是会调用Dispatcher的finished函数,打开源码,发现它将正在运行的任务Call从队列runningAsyncCalls中移除后,接着执行promoteCalls()函数

这样,就主动的把缓存队列向前走了一步,而没有使用互斥锁等复杂编码.

通过上述的分析,我们知道了:

  1. OkHttp采用Dispatcher技术,类似于Nginx,与线程池配合实现了高并发,低阻塞的运行
  2. Okhttp采用Deque作为缓存,按照入队的顺序先进先出
  3. OkHttp最出彩的地方就是在try/finally中调用了finished函数,可以主动控制等待队列的移动,而不是采用锁或者wait/notify,极大减少了编码复杂性

地址:

http://www.jianshu.com/p/aad5aacd79bf


05-11 18:12