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

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() < connection.allocationLimit

&& address.equals(connection.route().address)

&& !connection.noNewStreams) {

streamAllocation.acquire(connection);

return connection;

}

}

return null;

}

遍历connections缓存列表,当某个连接计数的次数小于限制的大小以及request的地址和缓存列表中此连接的地址完全匹配。则直接复用缓存列表中的connection作为request的连接。

streamAllocation.allocations是个对象计数器,其本质是一个 List<Reference> 存放在RealConnection连接对象中用于记录Connection的活跃情况。

连接池中Connection的缓存比较简单,就是利用一个双端列表,配合CRD等操作。那么connection在timeout时间类是如果失效的呢,并且如果做到有效的对连接进行清除操作以确保性能和内存空间的充足。

2.2 连接池的清理和回收

在看ConnectionPool的成员变量的时候我们了解到一个Executor的线程池是用来清理闲置的连接的。注释中是这么解释的:

Background threads are used to cleanup expired connections

我们在put新连接到队列的时候会先执行清理闲置连接的线程。调用的正是 executor.execute(cleanupRunnable); 方法。观察cleanupRunnable

private final Runnable cleanupRunnable = new Runnable() {

@Override public void run() {

while (true) {

long waitNanos = cleanup(System.nanoTime());

if (waitNanos == -1) return;

if (waitNanos > 0) {

long waitMillis = waitNanos / 1000000L;

waitNanos -= (waitMillis * 1000000L);

synchronized (ConnectionPool.this) {

try {

ConnectionPool.this.wait(waitMillis, (int) waitNanos);

} catch (InterruptedException ignored) {

}

}

}

}

}

};

线程中不停调用Cleanup 清理的动作并立即返回下次清理的间隔时间。继而进入wait 等待之后释放锁,继续执行下一次的清理。所以可能理解成他是个监测时间并释放连接的后台线程。

了解cleanup动作的过程。这里就是如何清理所谓闲置连接的和行了。怎么找到闲置的连接是主要解决的问题。

long cleanup(long now) {

int inUseConnectionCount = 0;

int idleConnectionCount = 0;

RealConnection longestIdleConnection = null;

long longestIdleDurationNs = Long.MIN_VALUE;

// Find either a connection to evict, or the time that the next eviction is due.

synchronized (this) {

for (Iterator i = connections.iterator(); i.hasNext(); ) {

RealConnection connection = i.next();

// If the connection is in use, keep searching.

if (pruneAndGetAllocationCount(connection, now) > 0) {

inUseConnectionCount++;

continue;

}

idleConnectionCount++;

// If the connection is ready to be evicted, we’re done.

long idleDurationNs = now - connection.idleAtNanos;

if (idleDurationNs > longestIdleDurationNs) {

longestIdleDurationNs = idleDurationNs;

longestIdleConnection = connection;

}

}

if (longestIdleDurationNs >= this.keepAliveDurationNs

|| idleConnectionCount > this.maxIdleConnections) {

// We’ve found a connection to evict. Remove it from the list, then close it below (outside

// of the synchronized block).

connections.remove(longestIdleConnection);

} else if (idleConnectionCount > 0) {

// A connection will be ready to evict soon.

return keepAliveDurationNs - longestIdleDurationNs;

} else if (inUseConnectionCount > 0) {

// All connections are in use. It’ll be at least the keep alive duration 'til we run again.

return keepAliveDurationNs;

} else {

// No connections, idle or in use.

cleanupRunning = false;

return -1;

}

}

closeQuietly(longestIdleConnection.socket());

// Cleanup again immediately.

return 0;

}

在遍历缓存列表的过程中,使用连接数目inUseConnectionCount 和闲置连接数目idleConnectionCount 的计数累加值都是通过pruneAndGetAllocationCount() 是否大于0来控制的。那么很显然pruneAndGetAllocationCount() 方法就是用来识别对应连接是否闲置的。>0则不闲置。否则就是闲置的连接。

进去观察

private int pruneAndGetAllocationCount(RealConnection connection, long now) {

List<Reference> references = connection.allocations;

for (int i = 0; i < references.size(); ) {

Reference reference = references.get(i);

if (reference.get() != null) {

i++;

continue;

}

// We’ve discovered a leaked allocation. This is an application bug.

Platform.get().log(WARN, "A connection to " + connection.route().address().url()

  • " was leaked. Did you forget to close a response body?", null);

references.remove(i);

connection.noNewStreams = true;

// If this was the last allocation, the connection is eligible for immediate eviction.

if (references.isEmpty()) {

connection.idleAtNanos = now - keepAliveDurationNs;

return 0;

}

}

return references.size();

}

总结

**其实上面说了这么多,钱是永远赚不完的,在这个知识付费的时代,知识技能提升才是是根本!我作为一名8年的高级工程师,知识技能已经学习的差不多。**在看这篇文章的可能有刚刚入门,刚刚开始工作,或者大佬级人物。

像刚刚开始学Android开发小白想要快速提升自己,最快捷的方式,就是有人可以带着你一起分析,这样学习起来最为高效,所以这里分享一套高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。

这么重要的事情说三遍啦!点赞+点赞+点赞!

【Android高级架构师系统学习资料】高级架构师进阶必备——设计思想解读开源框架

第一章、热修复设计
第二章、插件化框架设计
第三章、组件化框架设计
第四章、图片加载框架
第五章、网络访问框架设计
第六章、RXJava 响应式编程框架设计
第七章、IOC 架构设计
第八章、Android 架构组件 Jetpack

高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。

这么重要的事情说三遍啦!点赞+点赞+点赞!
[外链图片转存中…(img-NzMSe3rJ-1720098209274)]

【Android高级架构师系统学习资料】高级架构师进阶必备——设计思想解读开源框架

第一章、热修复设计
第二章、插件化框架设计
第三章、组件化框架设计
第四章、图片加载框架
第五章、网络访问框架设计
第六章、RXJava 响应式编程框架设计
第七章、IOC 架构设计
第八章、Android 架构组件 Jetpack

[外链图片转存中…(img-iL8B7x2V-1720098209275)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值