關於HttpClient 引發的執行緒太多導致FullGc的問題
阿新 • • 發佈:2021-01-12
CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setMaxConnTotal(400) .setMaxConnPerRoute(150) .evictExpiredConnections() .build();
evictExpiredConnections 這個配置作用:
設定一個定時執行緒,定時清理閒置連線,可以將這個定時時間設定為 keep alive timeout 時間的一半以保證超時前回收
每個httpClient 物件都會有自己獨立的定時執行緒
這樣如果應用中httpClient物件很多,就會導致上圖中執行緒太多
原始碼中,如果設定了evictExpiredConnections 會有下面一段邏輯
List<Closeable> closeablesCopy = closeables != null ? new ArrayList<Closeable>(closeables) : null; if (!this.connManagerShared) { if (closeablesCopy == null) { closeablesCopy = new ArrayList<Closeable>(1); } final HttpClientConnectionManager cm = connManagerCopy; if (evictExpiredConnections || evictIdleConnections) { final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm,maxIdleTime > 0 ? maxIdleTime : 10,maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS,maxIdleTime,maxIdleTimeUnit); closeablesCopy.add(new Closeable() { @Override public void close() throws IOException { connectionEvictor.shutdown(); try { connectionEvictor.awaitTermination(1L,TimeUnit.SECONDS); } catch (final InterruptedException interrupted) { Thread.currentThread().interrupt(); } } }); connectionEvictor.start(); } closeablesCopy.add(new Closeable() { @Override public void close() throws IOException { cm.shutdown(); } }); }
IdleConnectionEvictor 物件是
public final class IdleConnectionEvictor { private final HttpClientConnectionManager connectionManager; private final ThreadFactory threadFactory; private final Thread thread; private final long sleepTimeMs; private final long maxIdleTimeMs; private volatile Exception exception; public IdleConnectionEvictor( final HttpClientConnectionManager connectionManager,final ThreadFactory threadFactory,final long sleepTime,final TimeUnit sleepTimeUnit,final long maxIdleTime,final TimeUnit maxIdleTimeUnit) { this.connectionManager = Args.notNull(connectionManager,"Connection manager"); this.threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory(); this.sleepTimeMs = sleepTimeUnit != null ? sleepTimeUnit.toMillis(sleepTime) : sleepTime; this.maxIdleTimeMs = maxIdleTimeUnit != null ? maxIdleTimeUnit.toMillis(maxIdleTime) : maxIdleTime; this.thread = this.threadFactory.newThread(new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { Thread.sleep(sleepTimeMs); connectionManager.closeExpiredConnections(); if (maxIdleTimeMs > 0) { connectionManager.closeIdleConnections(maxIdleTimeMs,TimeUnit.MILLISECONDS); } } } catch (final Exception ex) { exception = ex; } } }); }
會出現一個執行緒,這個執行緒裡面就是去關閉超時不用的閒置連結
到此這篇關於關於HttpClient 引發的執行緒太多導致FullGc的問題的文章就介紹到這了,更多相關HttpClient 引發的執行緒太多導致FullGc內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!