OkHttp 源码解析(三)

简介

上一篇文章分析了 OkHttp 建立连接的过程,主要涉及到的几个类包括 StreamAllocation、RealConnection 以及 HttpCodec,其中 RealConnection 封装了底层的 Socket。Socket 建立了 TCP 连接,这是需要消耗时间和资源的,而 OkHttp 则使用连接池来管理这里连接,进行连接的重用,提高请求的效率。OkHttp 中的连接池由 ConnectionPool 实现,本文主要是对这个类进行分析。

get 和 put

在 StreamAllocation 的 findConnection 方法中,有这样一段代码:

// 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 中的代码:

@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;
}

connections 是 ConnectionPool 中的一个队列:

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

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

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 逻辑还是比较简单明了的。

接下来看一下 put,在 StreamAllocation 的 findConnection 方法中,如果新创建了 Connection,则将其放到连接池中。

Internal.instance.put(connectionPool, result);

最终调用的是 ConnectionPool#put:

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

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

cleanup

线程池需要对闲置的或者超时的连接进行清理,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) {
            }
          }
        }
      }
    }
};

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 的引用,则表示StreamAllocation 中 release(RealConnection connection) 方法未被调用,可能是读取 ResponseBody 没有关闭 I/O 导致的。

总结

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

点赞