OkHttp3源码详解之-okhttp连接池复用机制(一)

本文详细解析了OkHttp3的连接池复用机制,包括缓存操作和连接池的清理与回收。缓存操作涉及put、get、connectionBecameIdle和evictAll方法,连接池通过一个线程池定时清理过期连接。文章还介绍了如何找到并关闭闲置连接,以及在清理过程中如何判断连接是否可复用。
摘要由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.holdsLo

  • 16
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值