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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值