OkHttp3源码详解(五)okhttp连接池复用机制

OkHttp3的连接池使用一个线程池执行清理任务,避免闲置连接浪费资源。连接池通过Deque缓存RealConnection,使用Executor执行清理线程,检查并回收超时或未使用的连接。在put新连接时会触发清理,get方法根据条件复用已有的连接。清理过程会判断连接是否超时或达到最大闲置连接数,以便有效管理连接池。
摘要由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) {

if (connection.allocations.size() &

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值