OkHttp 源码解析(三):链接池

简介

上一篇文章(OkHttp 源码解析(二):创建链接)分析了 OkHttp 创建链接的过程,主要涉及到的几个类包括 StreamAllocationRealConnection 以及 HttpCodec,其中 RealConnection 封装了底层的 Socket。Socket 创建了 TCP 链接,这是须要消耗时间和资源的,而 OkHttp 则使用链接池来管理这里链接,进行链接的重用,提升请求的效率。OkHttp 中的链接池由 ConnectionPool 实现,本文主要是对这个类进行分析。java

get 和 put

StreamAllocationfindConnection 方法中,有这样一段代码:segmentfault

// Attempt to get a connection from the pool.
Internal.instance.get(connectionPool, address, this, null);
    if (connection != null) {
        return connection;
}

Internal.instance.get 最终是从 ConnectionPool 取得一个RealConnection, 若是有了则直接返回。下面是 ConnectionPool 中的代码:app

@Nullable RealConnection get(Address address, StreamAllocation streamAllocation, Route route) {
    assert (Thread.holdsLock(this));
    for (RealConnection connection : connections) {
      if (connection.isEligible(address, route)) {
        streamAllocation.acquire(connection);
        return connection;
      }
    }
    return null;
}

connectionsConnectionPool 中的一个队列:socket

private final Deque<RealConnection> connections = new ArrayDeque<>();

从队列中取出一个 Connection 以后,判断其是否能知足重用的要求:ide

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.
    }
   // 省略 http2 相关代码
   ...
}

boolean equalsNonHost(Address that) {
    return this.dns.equals(that.dns)
        && this.proxyAuthenticator.equals(that.proxyAuthenticator)
        && this.protocols.equals(that.protocols)
        && this.connectionSpecs.equals(that.connectionSpecs)
        && this.proxySelector.equals(that.proxySelector)
        && equal(this.proxy, that.proxy)
        && equal(this.sslSocketFactory, that.sslSocketFactory)
        && equal(this.hostnameVerifier, that.hostnameVerifier)
        && equal(this.certificatePinner, that.certificatePinner)
        && this.url().port() == that.url().port();
}

若是这个 Connection 已经分配的数量超过了分配限制或者被标记为不能再分配,则直接返回 false,不然调用 equalsNonHost,主要是判断 Address 中除了 host 之外的变量是否相同,若是有不一样的,那么这个链接也不能重用。最后就是判断 host 是否相同,若是相同那么对于当前的 Address 来讲, 这个 Connection 即是可重用的。从上面的代码看来,get 逻辑仍是比较简单明了的。ui

接下来看一下 put,在 StreamAllocationfindConnection 方法中,若是新建立了 Connection,则将其放到链接池中。this

Internal.instance.put(connectionPool, result);

最终调用的是 ConnectionPool#puturl

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

首先判断其否启动了清理线程,若是没有则将 cleanupRunnable 放到线程池中。最后是将 RealConnection 放到队列中。线程

cleanup

线程池须要对闲置的或者超时的链接进行清理,CleanupRunnable 就是作这件事的:code

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) {
            }
          }
        }
      }
    }
};

run 里面有个无限循环,调用 cleanup 以后,获得一个时间 waitNano,若是不为 -1 则表示线程的睡眠时间,接下来调用 wait 进入睡眠。若是是 -1,则表示当前没有须要清理的链接,直接返回便可。

清理的主要实如今 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<RealConnection> i = connections.iterator(); i.hasNext(); ) {
        RealConnection connection = i.next();

        // If the connection is in use, keep searching.
        // 1. 判断是不是空闲链接
        if (pruneAndGetAllocationCount(connection, now) > 0) {
          inUseConnectionCount++;
          continue;
        }

        idleConnectionCount++;

        // If the connection is ready to be evicted, we're done.
        // 2. 判断是不是最长空闲时间的链接
        long idleDurationNs = now - connection.idleAtNanos;
        if (idleDurationNs > longestIdleDurationNs) {
          longestIdleDurationNs = idleDurationNs;
          longestIdleConnection = connection;
        }
      }
        //  3. 若是最长空闲的时间超过了设定的最大值,或者空闲连接数量超过了最大数量,则进行清理,不然计算下一次须要清理的等待时间
      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;
      }
    }
     // 3. 关闭链接的socket
    closeQuietly(longestIdleConnection.socket());

    // Cleanup again immediately.
    return 0;
}

清理的逻辑大体是如下几步:

  1. 遍历全部的链接,对每一个链接调用 pruneAndGetAllocationCount 判断其是否闲置的链接。若是是正在使用中,则直接遍历一下个。
  2. 对于闲置的链接,判断是不是当前空闲时间最长的。
  3. 对于当前空闲时间最长的链接,若是其超过了设定的最长空闲时间(5分钟)或者是最大的空闲链接的数量(5个),则清理此链接。不然计算下次须要清理的时间,这样 cleanupRunnable 中的循环变会睡眠相应的时间,醒来后继续清理。

pruneAndGetAllocationCount 用于清理可能泄露的 StreamAllocation 并返回正在使用此链接的 StreamAllocation 的数量,代码以下:

private int pruneAndGetAllocationCount(RealConnection connection, long now) {
    List<Reference<StreamAllocation>> references = connection.allocations;
    for (int i = 0; i < references.size(); ) {
      Reference<StreamAllocation> reference = references.get(i);

      if (reference.get() != null) {
        i++;
        continue;
      }

      // We've discovered a leaked allocation. This is an application bug.
      // 若是 StreamAlloction 引用被回收,可是 connection 的引用列表中扔持有,那么可能发生了内存泄露
      StreamAllocation.StreamAllocationReference streamAllocRef =
          (StreamAllocation.StreamAllocationReference) reference;
      String message = "A connection to " + connection.route().address().url()
          + " was leaked. Did you forget to close a response body?";
      Platform.get().logCloseableLeak(message, streamAllocRef.callStackTrace);

      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();
}

若是 StreamAllocation 已经被回收,说明应用层的代码已经不须要这个链接,可是 Connection 仍持有 StreamAllocation 的引用,则表示StreamAllocationrelease(RealConnection connection) 方法未被调用,多是读取 ResponseBody 没有关闭 I/O 致使的。

总结

OkHttp 中的链接池主要就是保存一个正在使用的链接的队列,对于知足条件的同一个 host 的多个链接复用同一个 RealConnection,提升请求效率。此外,还会启动线程对闲置超时或者超出闲置数量的 RealConnection 进行清理。

若是个人文章对您有帮助,不妨点个赞支持一下(^_^)

相关文章
相关标签/搜索