安卓开发博客Android技术知识Android开发

OkHttp3架构分析

2018-03-29  本文已影响786人  Jdqm

在OkHttp3中,其灵活性很大程度上体现在,可以intercept其任意一个环节,而这个优势便是okhttp3整个请求响应架构体系的精髓所在:


Okhttp请求流程 完整interceptor-chain

OkHttp3中的线程池

OkHttp 中的对所有的任务采用 NamedRunnable,约束每个执行单元给出对应的业务名称,以便于线程维护。

1.异步请求线程池-OkHttp 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;
  }
okHttpClient.dispatcher().setMaxRequests(128);
okHttpClient.dispatcher().setMaxRequestsPerHost(10);
异步请求线程池

2.连接池清理线程池-OkHttp ConnectionPool

/**
* Background threads are used to cleanup expired connections. There will be at most a single
* thread running per connection pool. The thread pool executor permits the pool itself to be
* garbage collected.
*/
private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
    Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
    new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));
void put(RealConnection connection) {
    assert (Thread.holdsLock(this));
    if (!cleanupRunning) {
        cleanupRunning = true;
        executor.execute(cleanupRunnable);
    }
    connections.add(connection);
}
void put(RealConnection connection) {
    assert (Thread.holdsLock(this));
    if (!cleanupRunning) {
        cleanupRunning = true;
        executor.execute(cleanupRunnable);
    }
    connections.add(connection);
  }
连接池清理线程池

3. 缓存整理线程池-OkHttp DiskLruCache

// Use a single background thread to evict entries.
Executor executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
    new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true));

4. HTTP2异步事务线程池-OkHttp Http2Connection

相关阅读

上一篇 下一篇

猜你喜欢

热点阅读