IEAD中加入阿里的程式碼檢查外掛後Executors提示需手動建立
轉自:https://blog.csdn.net/w605283073/article/details/80259493
最近了解一下執行緒池,下載其中的程式碼並執行。
https://howtodoinjava.com/core-java/multi-threading/when-to-use-countdownlatch-java-concurrency-example-tutorial/
其中ApplicationStartupUtil這個類
-
package com.chujianyun;
-
import com.chujianyun.verifier.BaseHealthChecker;
-
import com.chujianyun.verifier.CacheHealthChecker;
-
import com.chujianyun.verifier.DatabaseHealthChecker;
-
import com.chujianyun.verifier.NetworkHealthChecker;
-
import java.util.concurrent.*;
-
public class ApplicationStartupUtil
-
{
-
private static BlockingQueue
<Runnable
> services;
-
private static CountDownLatch latch;
-
-
private ApplicationStartupUtil()
-
{
-
}
-
-
private final static ApplicationStartupUtil INSTANCE = new ApplicationStartupUtil();
-
-
public static ApplicationStartupUtil getInstance()
-
{
-
return INSTANCE;
-
}
-
-
public static boolean checkExternalServices() throws Exception
-
{
-
latch = new CountDownLatch(3);
-
services = new ArrayBlockingQueue
<>(3);
-
services.add(new NetworkHealthChecker(latch));
-
services.add(new CacheHealthChecker(latch));
-
services.add(new DatabaseHealthChecker(latch));
-
-
ExecutorService executorService = Executors.newFixedThreadPool(services.size());
-
for(final Runnable v : services)
-
{
-
executorService.execute(v);
-
}
-
latch.await();
-
-
for(final Runnable v : services)
-
{
-
BaseHealthChecker baseHealthChecker = (BaseHealthChecker) v;
-
if( ! baseHealthChecker.isServiceUp())
-
{
-
return false;
-
}
-
}
-
return true;
-
}
-
}
其中有下面程式碼:
ExecutorService executorService = Executors.newFixedThreadPool(services.size());
由於IDEA安裝了阿里的Java程式設計規範檢查外掛,提示讓手動建立執行緒池。
1、修改程式碼
檢視newFixedThreadPool函式原始碼:
-
/**
-
* Creates a thread pool that reuses a fixed number of threads
-
* operating off a shared unbounded queue. At any point, at most
-
* {@code nThreads} threads will be active processing tasks.
-
* If additional tasks are submitted when all threads are active,
-
* they will wait in the queue until a thread is available.
-
* If any thread terminates due to a failure during execution
-
* prior to shutdown, a new one will take its place if needed to
-
* execute subsequent tasks. The threads in the pool will exist
-
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
-
*
-
* @param nThreads the number of threads in the pool
-
* @return the newly created thread pool
-
* @throws IllegalArgumentException if {@code nThreads
<= 0}
-
*/
-
public static ExecutorService newFixedThreadPool(int nThreads) {
-
return new ThreadPoolExecutor(nThreads, nThreads,
-
0L, TimeUnit.MILLISECONDS,
-
new LinkedBlockingQueue<Runnable>());
-
}
得知該函式最終呼叫的還是ThreadPoolExecutor構造方法。
因此上面一句可以改成:
-
int size = services.size();
-
ExecutorService executorService = new ThreadPoolExecutor(size,size,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue
<Runnable>());
但是又有提示,建議要為執行緒池中的執行緒設定名稱:
僅此在構造方法後加入TreadFactory,大功告成
-
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
-
int size = services.size();
-
ExecutorService executorService = new ThreadPoolExecutor(size,size,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue
<Runnable>(),namedThreadFactory);
2、為什麼要這麼做呢?
我們參考阿里巴巴的Java開發手冊內容:
8. 【強制】執行緒池不允許使用Executors去建立,而是通過ThreadPoolExecutor的方式,這樣的處理方式讓寫的同學更加明確執行緒池的執行規則,規避資源耗盡的風險。
說明:Executors各個方法的弊端:
1) newFixedThreadPool和newSingleThreadExecutor: 主要問題是堆積的請求處理佇列可能會耗費非常大的記憶體,甚至OOM。
2) newCachedThreadPool和newScheduledThreadPool: 主要問題是執行緒數最大數是Integer.MAX_VALUE,可能會建立數量非常多的執行緒,甚至OOM。
9. 【強制】建立執行緒或執行緒池時請指定有意義的執行緒名稱,方便出錯時回溯。
我在此簡單進一步解讀一下:
[1] newFixedThreadPool和newSingleThreadExecutor 由於最後一個引數即工作佇列是:
-
/**
-
* Creates a thread pool that reuses a fixed number of threads
-
* operating off a shared unbounded queue. At any point, at most
-
* {@code nThreads} threads will be active processing tasks.
-
* If additional tasks are submitted when all threads are active,
-
* they will wait in the queue until a thread is available.
-
* If any thread terminates due to a failure during execution
-
* prior to shutdown, a new one will take its place if needed to
-
* execute subsequent tasks. The threads in the pool will exist
-
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
-
*
-
* @param nThreads the number of threads in the pool
-
* @return the newly created thread pool
-
* @throws IllegalArgumentException if {@code nThreads <= 0}
-
*/
-
public static ExecutorService newFixedThreadPool(int nThreads) {
-
return
new ThreadPoolExecutor(nThreads, nThreads,
-
0L, TimeUnit.MILLISECONDS,
-
new LinkedBlockingQueue<Runnable>());
-
}
連結串列型別的阻塞佇列,而我們看其建構函式發現,預設佇列大小是整數的最大值!!
-
/**
-
* Creates a {@code LinkedBlockingQueue} with a capacity of
-
* {@link Integer#MAX_VALUE}.
-
*/
-
public LinkedBlockingQueue() {
-
this(Integer.MAX_VALUE);
-
}
-
-
/**
-
* Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
-
*
-
* @param capacity the capacity of this queue
-
* @throws IllegalArgumentException if {@code capacity} is not greater
-
* than zero
-
*/
-
public LinkedBlockingQueue(int capacity) {
-
if (capacity <=
0)
throw
new IllegalArgumentException();
-
this.capacity = capacity;
-
last = head =
new Node<E>(
null);
-
}
所以如果請求太多,佇列很可能就耗費記憶體非常大導致OOM.
但是他們的執行緒數是固定的,而且一般不會太大,所以不會因為建立過多執行緒而導致OOM。
[2]newCachedThreadPool和newScheduledThreadPool:
-
/**
-
* Creates a thread pool that creates new threads as needed, but
-
* will reuse previously constructed threads when they are
-
* available. These pools will typically improve the performance
-
* of programs that execute many short-lived asynchronous tasks.
-
* Calls to {@code execute} will reuse previously constructed
-
* threads if available. If no existing thread is available, a new
-
* thread will be created and added to the pool. Threads that have
-
* not been used for sixty seconds are terminated and removed from
-
* the cache. Thus, a pool that remains idle for long enough will
-
* not consume any resources. Note that pools with similar
-
* properties but different details (for example, timeout parameters)
-
* may be created using {@link ThreadPoolExecutor} constructors.
-
*
-
* @return the newly created thread pool
-
*/
-
public static ExecutorService newCachedThreadPool() {
-
return
new ThreadPoolExecutor(
0, Integer.MAX_VALUE,
-
60L, TimeUnit.SECONDS,
-
new SynchronousQueue<Runnable>());
-
}
其中第最大執行緒池大小是整數的最大值,因此執行緒可能不斷建立,乃至到整數的最大值個執行緒,很容易導致OOM.
其中工作佇列使用的是 SynchronousQueue<E>
原始碼頭部的註釋中有說明
-
* A {
@linkplain BlockingQueue blocking queue} in which each insert
-
* operation must wait
for a corresponding remove operation by another
-
* thread, and vice versa. A synchronous queue does not have any
-
* internal capacity, not even a capacity of one. You cannot
-
* {
@code peek} at a synchronous queue because an element is only
-
* present when you
try to remove it; you cannot insert an element
-
* (using any method) unless another thread is trying to remove it;
-
* you cannot iterate as there is nothing to iterate. The
-
* <em>head</em> of the queue is the element that the first queued
-
* inserting thread is trying to add to the queue;
if there is no such
-
* queued thread then no element is available
for removal and
-
* {
@code poll()} will
return {
@code
null}. For purposes of other
-
* {
@code Collection} methods (
for example {
@code contains}), a
-
* {
@code SynchronousQueue} acts as an empty collection. This queue
-
* does not permit {
@code
null} elements.
可以看出
A {@linkplain BlockingQueue blocking queue} in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa.
該型別的阻塞佇列每一個插入操作必須等待對應的元素被另一個執行緒所移除,反之亦然。
因此阻塞佇列不會無限拓展而導致OOM。
因此我們理解一些原則的時候,學習的時候多注重原始碼分析非常有必要,其他細節有待以後深入研究。
參考文章:http://www.crazyant.net/2124.html
最近了解一下執行緒池,下載其中的程式碼並執行。