??分析完了攔截器悔耘,感覺意猶未盡。其實(shí)在分析攔截器我擂,就已經(jīng)涉及到連接池的概念衬以,但是當(dāng)時(shí)只是一筆帶過缓艳,本來打算寫在系列(三)中的。但是寫下來的話看峻,估計(jì)篇幅比較大阶淘,所以打算單獨(dú)開一篇文章來分析ConnectionPool
。
1. 概述
??在整個(gè)OkHttp的流程中互妓,我們?cè)谀睦锟吹竭^ConnectionPool
的身影呢溪窒?
??首先,在OKHttpClient.Builder
的構(gòu)造方法里面冯勉,對(duì)ConnectionPool
進(jìn)行了初始化澈蚌。我還記得,當(dāng)時(shí)我在分析OKHttpClient.Builder
的構(gòu)造方法時(shí)灼狰,當(dāng)時(shí)說后面會(huì)詳細(xì)的講解它宛瞄。這不,如約而至交胚。
??其次份汗,我們還在StreamAllocation
的newStream
方法看到過ConnectionPool
。StreamAllocation
在調(diào)用findConnection
方法尋找一個(gè)可以使用Connection
蝴簇,這里也涉及到ConnectionPool
杯活。findConnection
方法在尋找Connection
時(shí),首先會(huì)嘗試復(fù)用StreamAllocation
本身的Connection
,如果這個(gè)Connection
不可用的話熬词,那么就會(huì)去ConnectionPool
去尋找合適的Connection
旁钧。
??總的來說,ConnectionPool
負(fù)責(zé)所有的連接荡澎,包括連接的復(fù)用均践,以及無用連接的清理晤锹。本文也從這兩個(gè)方面對(duì)ConnectionPool
進(jìn)行分析摩幔。
2. get方法和put方法
??外部通過調(diào)用get
方法來獲取一個(gè)可以使用Connection
對(duì)象,通過put
方法添加一個(gè)新的連接。我們來具體的看看鞭铆,這兩個(gè)方法究竟做了那些事情或衡。
(1). get方法
??get
方法是從連接池里面獲取一個(gè)連接供使用。
@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;
}
??其實(shí)get
方法表達(dá)的意思比較簡(jiǎn)單车遂,就是遍歷connections
,找到一個(gè)合適的連接封断。判斷一個(gè)連接是否可以使用,是通過isEligible
方法實(shí)現(xiàn)的舶担。
??isEligible
方法內(nèi)部主要是通過判斷當(dāng)前Connection
擁有的StreamAllocation
是否超過的限制坡疼,或者當(dāng)前Connection
是否不允許分配stream
等等途徑,進(jìn)而判斷當(dāng)前Connection
是否有效衣陶。
??為什么需要判斷Connection
擁有的StreamAllocation
是否超過的限制呢柄瑰?因?yàn)樵?code>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
方法里面闸氮,我們可以發(fā)現(xiàn),首先給StreamAllocation
的connection
賦值教沾;其次蒲跨,把當(dāng)前的StreamAllocation
對(duì)象添加到connection
的allocations
數(shù)組里面,表示當(dāng)前的Connection
被分配給這個(gè)StreamAllocation
授翻。
??看完了get
方法或悲,我們?cè)趤砜纯?code>put方法。
(2).put方法
??直接來看看put方法的實(shí)現(xiàn):
void put(RealConnection connection) {
assert (Thread.holdsLock(this));
if (!cleanupRunning) {
cleanupRunning = true;
executor.execute(cleanupRunnable);
}
connections.add(connection);
}
??put
方法表達(dá)的意思更加簡(jiǎn)單堪唐,直接將Connection
對(duì)象添加到connections
數(shù)組巡语。不過這里有一個(gè)地方需要注意,就是如果cleanupRunning
為false
羔杨,就會(huì)想線程池里面添加一個(gè)cleanupRunnable
捌臊,這里的目的進(jìn)行清理操作。這個(gè)馬上就會(huì)說兜材。
??總的來說理澎,ConnectionPool
的get
方法和put
方法還是比較簡(jiǎn)單的。接下來我們來看看ConnectionPool
的清理操作曙寡。
3. 清理無用的連接
??從上面我們已經(jīng)知道糠爬,ConnectionPool
是通過一個(gè)cleanupRunnable
來完成清理工作的。我們來看看cleanupRunnable
的實(shí)現(xiàn):
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) {
}
}
}
}
}
};
??這個(gè)cleanupRunnable
是一個(gè)死循環(huán)的任務(wù)举庶,只要cleanup
方法不返回-1执隧,就會(huì)一直執(zhí)行。
??當(dāng)cleanup
方法沒有返回-1户侥,當(dāng)前的Runnable
就會(huì)進(jìn)入睡眠狀態(tài)镀琉。看來真正的操作是在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
方法里面體現(xiàn)的淋漓盡致屋摔。我們具體的分析cleanup
方法。
??首先替梨,通過for循環(huán)找到當(dāng)前正在使用的Connection
數(shù)量和未使用的Connection
數(shù)量钓试,還有最大空閑時(shí)間和最大空閑時(shí)間的Connection
亡嫌,這些在下面的判斷都是用的丰滑。
??找到的最大空閑時(shí)間跟默認(rèn)的最大空閑時(shí)間比較躺酒,如果大于的話岩齿,表示當(dāng)前Connection
已經(jīng)超過了最大的空閑時(shí)間嫌吠,應(yīng)該被回收外恕,所以我們看到它會(huì)被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);
}
??如果當(dāng)前已經(jīng)有了空閑的Connection
媚赖,那么就會(huì)keepAliveDurationNs - longestIdleDurationNs
,表示當(dāng)前的cleanupRunnable
還需要睡眠keepAliveDurationNs - longestIdleDurationNs
時(shí)間漏隐,至于為什么是這么多,大家可以想一想信认,這里就不做過多的解釋串稀。
??其次,就是如果當(dāng)前還有正在使用的Connection
,那么當(dāng)前的cleanupRunnable
還需要沉睡keepAliveDurationNs
狮杨。這個(gè)上面的意思差不多母截。
??如果當(dāng)前既沒有空閑的Connection
,又沒有正在使用的Connection
橄教,那么表示當(dāng)前的ConnectionPool
已經(jīng)空了清寇,可以被回收了。
4. 總結(jié)
??ConnectionPool
還是比較簡(jiǎn)單的护蝶,這里對(duì)它進(jìn)行一個(gè)簡(jiǎn)單的總結(jié)华烟。
??1.get
方法可以從ConnectionPool
里面獲取一個(gè)Connection
。如果獲取成功持灰,則會(huì)在Connection
的allocations
添加對(duì)應(yīng)的StreamAllocation
盔夜,表示當(dāng)前Connection
被分配給一個(gè)StreamAllocation
。這個(gè)會(huì)成為判斷當(dāng)前Connection
是否有效的依據(jù)堤魁。
??2.put
方法在第一次調(diào)用時(shí)會(huì)啟動(dòng)一個(gè)清理線程喂链。這個(gè)清理線程只會(huì)在當(dāng)前ConnectionPool
為空時(shí)才會(huì)退出。