分析完了拦截器,感觉意犹未尽。其实在分析拦截器,就已经涉及到连接池的概念,但是当时只是一笔带过,本来打算写在系列(三)中的。但是写下来的话,估计篇幅比较大,所以打算单独开一篇文章来分析ConnectionPool。
1. 概述
在整个OkHttp的流程中,我们在哪里看到过ConnectionPool的身影呢?
首先,在OKHttpClient.Builder的构造方法里面,对ConnectionPool进行了初始化。我还记得,当时我在分析OKHttpClient.Builder的构造方法时,当时说后面会详细的讲解它。这不,如约而至。
其次,我们还在StreamAllocation的newStream方法看到过ConnectionPool。StreamAllocation在调用findConnection方法寻找一个可以使用Connection,这里也涉及到ConnectionPool。findConnection方法在寻找Connection时,首先会尝试复用StreamAllocation本身的Connection,如果这个Connection不可用的话,那么就会去ConnectionPool去寻找合适的Connection。
总的来说,ConnectionPool负责所有的连接,包括连接的复用,以及无用连接的清理。本文也从这两个方面对ConnectionPool进行分析。
2. get方法和put方法
外部通过调用get方法来获取一个可以使用Connection对象,通过put方法添加一个新的连接。我们来具体的看看,这两个方法究竟做了那些事情。
(1). get方法
get方法是从连接池里面获取一个连接供使用。
@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, true);
return connection;
}
}
return null;
}
其实get方法表达的意思比较简单,就是遍历connections,找到一个合适的连接。判断一个连接是否可以使用,是通过isEligible方法实现的。
isEligible方法内部主要是通过判断当前Connection拥有的StreamAllocation是否超过的限制,或者当前Connection是否不允许分配stream等等途径,进而判断当前Connection是否有效。
为什么需要判断Connection拥有的StreamAllocation是否超过的限制呢?因为在StreamAllocation的acquire方法里面做了如此操作:
public void acquire(RealConnection connection, boolean reportedAcquired) {
assert (Thread.holdsLock(connectionPool));
if (this.connection != null) throw new IllegalStateException();
this.connection = connection;
this.reportedAcquired = reportedAcquired;
connection.allocations.add(new StreamAllocationReference(this, callStackTrace));
}
从acquire方法里面,我们可以发现,首先给StreamAllocation的connection赋值;其次,把当前的StreamAllocation对象添加到connection的allocations数组里面,表示当前的Connection被分配给这个StreamAllocation。
看完了get方法,我们在来看看put方法。
(2).put方法
直接来看看put方法的实现:
void put(RealConnection connection) {
assert (Thread.holdsLock(this));
if (!cleanupRunning) {
cleanupRunning = true;
executor.execute(cleanupRunnable);
}
connections.add(connection);
}
put方法表达的意思更加简单,直接将Connection对象添加到connections数组。不过这里有一个地方需要注意,就是如果cleanupRunning为false,就会想线程池里面添加一个cleanupRunnable,这里的目的进行清理操作。这个马上就会说。
总的来说,ConnectionPool的get方法和put方法还是比较简单的。接下来我们来看看ConnectionPool的清理操作。
3. 清理无用的连接
从上面我们已经知道,ConnectionPool是通过一个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) {
}
}
}
}
}
};
这个cleanupRunnable是一个死循环的任务,只要cleanup方法不返回-1,就会一直执行。
当cleanup方法没有返回-1,当前的Runnable就会进入睡眠状态。看来真正的操作是在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.
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;
}
ConnectionPool的清理操作在cleanup方法里面体现的淋漓尽致。我们具体的分析cleanup方法。
首先,通过for循环找到当前正在使用的Connection数量和未使用的Connection数量,还有最大空闲时间和最大空闲时间的Connection,这些在下面的判断都是用的。
找到的最大空闲时间跟默认的最大空闲时间比较,如果大于的话,表示当前Connection已经超过了最大的空闲时间,应该被回收,所以我们看到它会被remove掉:
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);
}
如果当前已经有了空闲的Connection,那么就会keepAliveDurationNs - longestIdleDurationNs,表示当前的cleanupRunnable还需要睡眠keepAliveDurationNs - longestIdleDurationNs时间,至于为什么是这么多,大家可以想一想,这里就不做过多的解释。
其次,就是如果当前还有正在使用的Connection,那么当前的cleanupRunnable还需要沉睡keepAliveDurationNs。这个上面的意思差不多。
如果当前既没有空闲的Connection,又没有正在使用的Connection,那么表示当前的ConnectionPool已经空了,可以被回收了。
4. 总结
ConnectionPool还是比较简单的,这里对它进行一个简单的总结。
1.get方法可以从ConnectionPool里面获取一个Connection。如果获取成功,则会在Connection的allocations添加对应的StreamAllocation,表示当前Connection被分配给一个StreamAllocation。这个会成为判断当前Connection是否有效的依据。
2.put方法在第一次调用时会启动一个清理线程。这个清理线程只会在当前ConnectionPool为空时才会退出。