HttpClient線程池原理

HttpClient線程池原理

1.cpool對象

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. class CPool extends AbstractConnPool<HttpRoute, ManagedHttpClientConnection, CPoolEntry> {  
  2.   
  3.     private static final AtomicLong COUNTER = new AtomicLong();  
  4.   
  5.     private final Log log = LogFactory.getLog(CPool.class);  
  6.     private final long timeToLive;  
  7.     private final TimeUnit tunit;  
  8.   
  9.     public CPool(  
  10.             final ConnFactory<HttpRoute, ManagedHttpClientConnection> connFactory,  
  11.             final int defaultMaxPerRoute, final int maxTotal,  
  12.             final long timeToLive, final TimeUnit tunit) {  
  13.         super(connFactory, defaultMaxPerRoute, maxTotal);  
  14.         this.timeToLive = timeToLive;  
  15.         this.tunit = tunit;  
  16.     }  
可以看到很重要的三個相關類是
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. HttpRoute, ManagedHttpClientConnection, CPoolEntry  
其中HttpRoute是記錄的要請求的遠程服務器的地址,ManagedHttpClientConnection是與遠程服務器的一個Http連接,CPoolEntry這個對象裏面記錄了HttpRoute與ManagedHttpClientConnection的一個對應關係

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. public abstract class AbstractConnPool<T, C, E extends PoolEntry<T, C>>  
  2.                                                implements ConnPool<T, E>, ConnPoolControl<T> {  
  3.   
  4.     private final Lock lock;  
  5.     private final ConnFactory<T, C> connFactory;  
  6.     private final Map<T, RouteSpecificPool<T, C, E>> routeToPool;  
  7.     private final Set<E> leased;  
  8.     private final LinkedList<E> available;  
  9.     private final LinkedList<PoolEntryFuture<E>> pending;  
  10.     private final Map<T, Integer> maxPerRoute;  
  11.   
  12.     private volatile boolean isShutDown;  
  13.     private volatile int defaultMaxPerRoute;  
  14.     private volatile int maxTotal;  
  15.     private volatile int validateAfterInactivity;  
而我們從上圖就可以看出CPoolEntry便是線程池裏面的一個個元素,而且Cpool裏面實際上還包含routeToPool這個小的線程池,routeToPool裏面都是相對於一個固定的HttpRoute所建立的所有鏈接。

先看從線程池裏面是如何過去鏈接的

 圖一

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. @Override  
  2. public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {  
  3.     Args.notNull(route, "Route");  
  4.     Asserts.check(!this.isShutDown, "Connection pool shut down");  
  5.     return new PoolEntryFuture<E>(this.lock, callback) {  
  6.   
  7.         @Override  
  8.         public E getPoolEntry(  
  9.                 final long timeout,  
  10.                 final TimeUnit tunit)  
  11.                     throws InterruptedException, TimeoutException, IOException {  
  12.             final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this);  
  13.             onLease(entry);  
  14.             return entry;  
  15.         }  
  16.   
  17.     };  
  18. }  

這兒每次都會返回一個futrue對象。

這個對象就是PoolEntryFuture對象,可以看到裏面的get方法

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. public T get(  
  2.         final long timeout,  
  3.         final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {  
  4.     Args.notNull(unit, "Time unit");  
  5.     this.lock.lock();  
  6.     try {  
  7.         if (this.completed) {  
  8.             return this.result;  
  9.         }  
  10.         this.result = getPoolEntry(timeout, unit);  
  11.         this.completed = true;  
  12.         if (this.callback != null) {  
  13.             this.callback.completed(this.result);  
  14.         }  
  15.         return result;  
  16.     } catch (final IOException ex) {  
  17.         this.completed = true;  
  18.         this.result = null;  
  19.         if (this.callback != null) {  
  20.             this.callback.failed(ex);  
  21.         }  
  22.         throw new ExecutionException(ex);  
  23.     } finally {  
  24.         this.lock.unlock();  
  25.     }  
  26. }  

這裏的getPoolEntry方法,正是上圖中紅色字體標明的內部類實現的方法

而我們繼續追蹤AbstractConnPool類的getPoolEntryBlocking方法,這個就是從連接池中取出來鏈接,如果取不到,就進入等待隊列,當有連接釋放時,在嘗試去獲取連接

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. private E getPoolEntryBlocking(  
  2.         final T route, final Object state,  
  3.         final long timeout, final TimeUnit tunit,  
  4.         final PoolEntryFuture<E> future)  
  5.             throws IOException, InterruptedException, TimeoutException {  
  6.   
  7.     Date deadline = null;  
  8.     if (timeout > 0) {  
  9.         deadline = new Date  
  10.             (System.currentTimeMillis() + tunit.toMillis(timeout));  
  11.     }  
  12.   
  13.     this.lock.lock();  
  14.     try {  
  15.         final RouteSpecificPool<T, C, E> pool = getPool(route);  
  16.         E entry = null;  
  17.         while (entry == null) {  
  18.             Asserts.check(!this.isShutDown, "Connection pool shut down");  
  19.             for (;;) {  
  20.                 entry = pool.getFree(state);  
  21.                 if (entry == null) {  
  22.                     break;  
  23.                 }  
  24.                 if (entry.isClosed() || entry.isExpired(System.currentTimeMillis())) {  
  25.                     entry.close();  
  26.                     this.available.remove(entry);  
  27.                     pool.free(entry, false);  
  28.                 } else {  
  29.                     break;  
  30.                 }  
  31.             }  
  32.             if (entry != null) {  
  33.                 this.available.remove(entry);  
  34.                 this.leased.add(entry);  
  35.                 return entry;  
  36.             }  
  37.   
  38.             // New connection is needed  
  39.             final int maxPerRoute = getMax(route);  
  40.             // Shrink the pool prior to allocating a new connection  
  41.             final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute);  
  42.             if (excess > 0) {  
  43.                 for (int i = 0; i < excess; i++) {  
  44.                     final E lastUsed = pool.getLastUsed();  
  45.                     if (lastUsed == null) {  
  46.                         break;  
  47.                     }  
  48.                     lastUsed.close();  
  49.                     this.available.remove(lastUsed);  
  50.                     pool.remove(lastUsed);  
  51.                 }  
  52.             }  
  53.   
  54.             if (pool.getAllocatedCount() < maxPerRoute) {  
  55.                 final int totalUsed = this.leased.size();  
  56.                 final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0);  
  57.                 if (freeCapacity > 0) {  
  58.                     final int totalAvailable = this.available.size();  
  59.                     if (totalAvailable > freeCapacity - 1) {  
  60.                         if (!this.available.isEmpty()) {  
  61.                             final E lastUsed = this.available.removeLast();  
  62.                             lastUsed.close();  
  63.                             final RouteSpecificPool<T, C, E> otherpool = getPool(lastUsed.getRoute());  
  64.                             otherpool.remove(lastUsed);  
  65.                         }  
  66.                     }  
  67.                     final C conn = this.connFactory.create(route);  
  68.                     entry = pool.add(conn);  
  69.                     this.leased.add(entry);  
  70.                     return entry;  
  71.                 }  
  72.             }  
  73.   
  74.             boolean success = false;  
  75.             try {  
  76.                 pool.queue(future);  
  77.                 this.pending.add(future);  
  78.                 success = future.await(deadline);   //如果獲取不到連接就等待
  79.             } finally {  
  80.                 // In case of 'success', we were woken up by the  
  81.                 // connection pool and should now have a connection  
  82.                 // waiting for us, or else we're shutting down.  
  83.                 // Just continue in the loop, both cases are checked.  
  84.                 pool.unqueue(future);  
  85.                 this.pending.remove(future);  
  86.             }  
  87.             // check for spurious wakeup vs. timeout  
  88.             if (!success && (deadline != null) &&  
  89.                 (deadline.getTime() <= System.currentTimeMillis())) {  
  90.                 break;  
  91.             }  
  92.         }  
  93.         throw new TimeoutException("Timeout waiting for connection");  
  94.     } finally {  
  95.         this.lock.unlock();  
  96.     }  
  97. }  
發佈了79 篇原創文章 · 獲贊 9 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章