Okhttp链接池的使用,看完这一篇你就懂了

本文深入探讨Okhttp连接池的清理和回收机制,特别是`cleanupRunnable`的执行过程,如何定时执行`cleanup`以防止内存泄露。重点分析了连接池如何通过`Reference`链表跟踪链接状态,以及`StreamAllocation`和`connection`的引用变化,以判断和管理活动及空闲连接,确保连接池高效且无泄漏。
摘要由CSDN通过智能技术生成
 并向connection持有的allocations中增加了一条新的流的弱引用
也就是往这条连接中增加了一条流。 
```

而其中的条件为isEligible,跟踪进去可以看到,具体的条件为

1.  当前这次连接的最大并发数没有达到上限
2.  两个address的其他参数相同
3.  两个address的url的host相同

若满足以上条件,则说明host是相同的可以直接复用,如果不满足以上条件的话,仍旧有机会使用连接(将连接合并):

1.  首先这个连接需要使用HTTP/2
2.  要与复用前的Ip address相同,且不能使用代理
3.  这个连接的服务器证书授权中,必须包括新的主机。
4.  锁定证书(certificatePinner)必须匹配主机

```
public boolean isEligible(Address address, @Nullable Route route) {
  // If this connection is not accepting new streams, we're done.
  if (allocations.size() >= allocationLimit || noNewStreams) return false;

  // If the non-host fields of the address don't overlap, we're done.
  if (!Internal.instance.equalsNonHost(this.route.address(), address)) return false;

  // If the host exactly matches, we're done: this connection can carry the address.
  if (address.url().host().equals(this.route().address().url().host())) {
    return true; // This connection is a perfect match.
  }

  // At this point we don't have a hostname match. But we still be able to carry the request if
  // our connection coalescing requirements are met. See also:
  // https://hpbn.co/optimizing-application-delivery/#eliminate-domain-sharding
  // https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/

  // 1. T
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值