上一篇文章(OkHttp 源碼解析(二):創建鏈接)分析了 OkHttp 創建鏈接的過程,主要涉及到的幾個類包括 StreamAllocation
、RealConnection
以及 HttpCodec
,其中 RealConnection
封裝了底層的 Socket。Socket 創建了 TCP 鏈接,這是須要消耗時間和資源的,而 OkHttp 則使用鏈接池來管理這裏鏈接,進行鏈接的重用,提升請求的效率。OkHttp 中的鏈接池由 ConnectionPool
實現,本文主要是對這個類進行分析。java
在 StreamAllocation
的 findConnection
方法中,有這樣一段代碼: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; }
connections
是 ConnectionPool
中的一個隊列: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
,在 StreamAllocation
的 findConnection
方法中,若是新建立了 Connection
,則將其放到鏈接池中。this
Internal.instance.put(connectionPool, result);
最終調用的是 ConnectionPool#put
:url
void put(RealConnection connection) { assert (Thread.holdsLock(this)); if (!cleanupRunning) { cleanupRunning = true; executor.execute(cleanupRunnable); } connections.add(connection); }
首先判斷其否啓動了清理線程,若是沒有則將 cleanupRunnable
放到線程池中。最後是將 RealConnection
放到隊列中。線程
線程池須要對閒置的或者超時的鏈接進行清理,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; }
清理的邏輯大體是如下幾步:
pruneAndGetAllocationCount
判斷其是否閒置的鏈接。若是是正在使用中,則直接遍歷一下個。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
進行清理。
若是個人文章對您有幫助,不妨點個贊支持一下(^_^)