17

android-网络框架解析–第1篇OkHttp(4.0.x)—OkHttpClient&Dispatcher

 3 years ago
source link: http://www.demanmath.com/index.php/2020/10/14/android-wangluokuangjiajiexi-di1pianokhttp4-0-x-okhttpclientdispatcher/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

OkHttpClinet

1.newCall
产生一个新call,核心是new,应为一个client可以对应很多个call。
从app的生命周期来讲,client可以是单例,call必须一个请求一个,call finish或者calcel以后,就结束了。
2.newWebSocket
websocket的使用及建立连接,主要用来建立长链接用的,一般网络框架不需要。
3.newBuilder
新的builder,内容一致

Dispatcher

调度并发的。创建线程池。request上限是64个。
Dispather处理这几个问题。

1.线程池
@get:Synchronized
@get:JvmName("executorService") val executorService: ExecutorService
get() {
if (executorServiceOrNull == null) {
executorServiceOrNull = ThreadPoolExecutor(0, Int.MAX_VALUE, 60, TimeUnit.SECONDS,
SynchronousQueue(), threadFactory("OkHttp Dispatcher", false))
}
return executorServiceOrNull!!
}

executorService 核心线程0个,最大线程max,线程最大空闲时间60s。

三个队列:
/* Ready async calls in the order they'll be run. /
private val readyAsyncCalls = ArrayDeque()

/* Running asynchronous calls. Includes canceled calls that haven't finished yet. /
private val runningAsyncCalls = ArrayDeque()

/* Running synchronous calls. Includes canceled calls that haven't finished yet. /
private val runningSyncCalls = ArrayDeque()

ArrayDeque 既可以是栈,也可以是队列使用。
readyAsyncCalls准备队列,还没有开始
runningAsyncCalls运行中的,包括calcel的call,还没有finished
runningSyncCalls运行中同步call,包括calcel的call,还没有finished
这里有个疑问,cancel是怎么做的?

promoteAndExecute:
把runningAsyncCalls放入到线程池进行running

2.同步调用
/* Used by Call#execute to signal it is in-flight. /
@Synchronized internal fun executed(call: RealCall) {
runningSyncCalls.add(call)
}

同步的方法没有开始执行任何操作,只是进行了记录。
getResponseWithInterceptorChain 这句就是开始执行call的动作。

再来看异步的AsyncCall的run方法,也是getResponseWithInterceptorChain这句代码。
整个http/https链接的过程就在这句代码开始。这个前面架构分析也有说到。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK