OkHttp3源码详解之-okhttp连接池复用机制(一),腾讯T2亲自讲解

本文深入探讨了OkHttp3的连接池复用机制,包括缓存操作、连接池的清理和回收。通过Executor线程池执行清理任务,确保过期连接被及时处理。在连接池中,利用Deque作为连接缓存,通过特定条件判断复用已存在的连接,从而提高性能。此外,还详细解析了如何检测和清理闲置连接。
摘要由CSDN通过智能技术生成
  • 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(), Util.threadFactory(“OkHttp ConnectionPool”, true));

/** The maximum number of idle connections for each address. */
private final int maxIdleConnections;

private final Deque connections = new ArrayDeque<>();
final RouteDatabase routeDatabase = new RouteDatabase();
boolean cleanupRunning;

excutor : 线程池,用来检测闲置socket并对其进行清理。
connections : connection缓存池。Deque是一个双端列表,支持在头尾插入元素,这里用作LIFO(后进先出)堆栈,多用于缓存数据。
routeDatabase :用来记录连接失败router

2.1 缓存操作

ConnectionPool提供对Deque进行操作的方法分别为put、get、connectionBecameIdle、evictAll几个操作。分别对应放入连接、获取连接、移除连接、移除所有连接操作。

put操作

void put(RealConnection connection) {
assert (Thread.holdsLock(this));
if (!cleanupRunning) {
cleanupRunning = true;
executor.execute(cleanupRunnable);
}
connections.add(connection);
}

可以看到在新的connection 放进列表之前执行清理闲置连接的线程。

既然是复用,那么看下他获取连接的方式。

/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
RealConnection get(Address address, StreamAllocation streamAllocation) {
assert (Thread.holdsLock(this));
for (RealConnection connection : connections) {

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值