【Java 併發編程】Java 創建線程池的正確姿勢: Executors 和 ThreadPoolExecutor 詳解...

我們先看 Java 開發手冊上說的:

我們可以看一下源碼:


這裏的 ThreadPoolExecutor 的構造函數如下:

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

參數說明:

類圖結構:

Executors的創建線程池的方法,創建出來的線程池都實現了ExecutorService接口。常用方法有以下幾個:

newFiexedThreadPool(int Threads):創建固定數目線程的線程池。

newCachedThreadPool():創建一個可緩存的線程池,調用execute 將重用以前構造的線程(如果線程可用)。如果沒有可用的線程,則創建一個新線程並添加到池中。終止並從緩存中移除那些已有 60 秒鐘未被使用的線程。

newSingleThreadExecutor()創建一個單線程化的Executor。

newScheduledThreadPool(int corePoolSize) 創建一個支持定時及週期性的任務執行的線程池,多數情況下可用來替代Timer類。

類看起來功能還是比較強大的,又用到了工廠模式、又有比較強的擴展性,重要的是用起來還比較方便,如:

ExecutorService executor = Executors.newFixedThreadPool(nThreads) ;

即可創建一個固定大小的線程池。

執行原理

線程池執行器將會根據corePoolSize和maximumPoolSize自動地調整線程池大小。

當在execute(Runnable)方法中提交新任務並且少於corePoolSize線程正在運行時,即使其他工作線程處於空閒狀態,也會創建一個新線程來處理該請求。 如果有多於corePoolSize但小於maximumPoolSize線程正在運行,則僅當隊列已滿時纔會創建新線程。 通過設置corePoolSize和maximumPoolSize相同,您可以創建一個固定大小的線程池。 通過將maximumPoolSize設置爲基本上無界的值,例如Integer.MAX_VALUE,您可以允許池容納任意數量的併發任務。 通常,核心和最大池大小僅在構建時設置,但也可以使用setCorePoolSize和setMaximumPoolSize進行動態更改。

這段話詳細了描述了線程池對任務的處理流程,這裏用個圖總結一下

使用 Executors 創建四種類型的線程池

newCachedThreadPool是Executors工廠類的一個靜態函數,用來創建一個可以無限擴大的線程池。

而Executors工廠類一共可以創建四種類型的線程池,通過Executors.newXXX即可創建。下面就分別都介紹一下。

1. FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads){
    return new ThreadPoolExecutor(nThreads,nThreads,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
}
  • 它是一種固定大小的線程池;
  • corePoolSize和maximunPoolSize都爲用戶設定的線程數量nThreads;
  • keepAliveTime爲0,意味着一旦有多餘的空閒線程,就會被立即停止掉;但這裏keepAliveTime無效;
  • 阻塞隊列採用了LinkedBlockingQueue,它是一個無界隊列;
  • 由於阻塞隊列是一個無界隊列,因此永遠不可能拒絕任務;
  • 由於採用了無界隊列,實際線程數量將永遠維持在nThreads,因此maximumPoolSize和keepAliveTime將無效。

2. CachedThreadPool

public static ExecutorService newCachedThreadPool(){
    return new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L,TimeUnit.MILLISECONDS,new SynchronousQueue<Runnable>());
}
  • 它是一個可以無限擴大的線程池;
  • 它比較適合處理執行時間比較小的任務;
  • corePoolSize爲0,maximumPoolSize爲無限大,意味着線程數量可以無限大;
  • keepAliveTime爲60S,意味着線程空閒時間超過60S就會被殺死;
  • 採用SynchronousQueue裝等待的任務,這個阻塞隊列沒有存儲空間,這意味着只要有請求到來,就必須要找到一條工作線程處理他,如果當前沒有空閒的線程,那麼就會再創建一條新的線程。

3. SingleThreadExecutor

public static ExecutorService newSingleThreadExecutor(){
    return new ThreadPoolExecutor(1,1,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
}
  • 它只會創建一條工作線程處理任務;
  • 採用的阻塞隊列爲LinkedBlockingQueue;

4. ScheduledThreadPool

它用來處理延時任務或定時任務。

  • 它接收SchduledFutureTask類型的任務,有兩種提交任務的方式:
  1. scheduledAtFixedRate
  2. scheduledWithFixedDelay
  • SchduledFutureTask接收的參數:
  1. time:任務開始的時間
  2. sequenceNumber:任務的序號
  3. period:任務執行的時間間隔
  • 它採用DelayQueue存儲等待的任務
  • DelayQueue內部封裝了一個PriorityQueue,它會根據time的先後時間排序,若time相同則根據sequenceNumber排序;
  • DelayQueue也是一個無界隊列;
  • 工作線程的執行過程:
  • 工作線程會從DelayQueue取已經到期的任務去執行;
  • 執行結束後重新設置任務的到期時間,再次放回DelayQueue

Executors存在什麼問題

在阿里巴巴Java開發手冊中提到,使用Executors創建線程池可能會導致OOM(OutOfMemory ,內存溢出),但是並沒有說明爲什麼,那麼接下來我們就來看一下到底爲什麼不允許使用Executors?

我們先來一個簡單的例子,模擬一下使用Executors導致OOM的情況。

/**
 * @author Hollis
 */
public class ExecutorsDemo {
    private static ExecutorService executor = Executors.newFixedThreadPool(15);
    public static void main(String[] args) {
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            executor.execute(new SubThread());
        }
    }
}

class SubThread implements Runnable {
    @Override
    public void run() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            //do nothing
        }
    }
}

通過指定JVM參數:-Xmx8m -Xms8m 運行以上代碼,會拋出OOM:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.util.concurrent.LinkedBlockingQueue.offer(LinkedBlockingQueue.java:416)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1371)
    at com.hollis.ExecutorsDemo.main(ExecutorsDemo.java:16)
以上代碼指出,ExecutorsDemo.java的第16行,就是代碼中的executor.execute(new SubThread());。

Executors爲什麼存在缺陷

通過上面的例子,我們知道了Executors創建的線程池存在OOM的風險,那麼到底是什麼原因導致的呢?我們需要深入Executors的源碼來分析一下。

其實,在上面的報錯信息中,我們是可以看出蛛絲馬跡的,在以上的代碼中其實已經說了,真正的導致OOM的其實是LinkedBlockingQueue.offer方法。

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.util.concurrent.LinkedBlockingQueue.offer(LinkedBlockingQueue.java:416)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1371)
    at com.hollis.ExecutorsDemo.main(ExecutorsDemo.java:16)

如果讀者翻看代碼的話,也可以發現,其實底層確實是通過LinkedBlockingQueue實現的:

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());

如果讀者對Java中的阻塞隊列有所瞭解的話,看到這裏或許就能夠明白原因了。

Java中的BlockingQueue主要有兩種實現,分別是ArrayBlockingQueue 和 LinkedBlockingQueue。

ArrayBlockingQueue是一個用數組實現的有界阻塞隊列,必須設置容量。

LinkedBlockingQueue是一個用鏈表實現的有界阻塞隊列,容量可以選擇進行設置,不設置的話,將是一個無邊界的阻塞隊列,最大長度爲Integer.MAX_VALUE。

這裏的問題就出在:不設置的話,將是一個無邊界的阻塞隊列,最大長度爲Integer.MAX_VALUE。也就是說,如果我們不設置LinkedBlockingQueue的容量的話,其默認容量將會是Integer.MAX_VALUE。

而newFixedThreadPool中創建LinkedBlockingQueue時,並未指定容量。此時,LinkedBlockingQueue就是一個無邊界隊列,對於一個無邊界隊列來說,是可以不斷的向隊列中加入任務的,這種情況下就有可能因爲任務過多而導致內存溢出問題。

上面提到的問題主要體現在newFixedThreadPool和newSingleThreadExecutor兩個工廠方法上,並不是說newCachedThreadPool和newScheduledThreadPool這兩個方法就安全了,這兩種方式創建的最大線程數可能是Integer.MAX_VALUE,而創建這麼多線程,必然就有可能導致OOM。

創建線程池的正確姿勢

避免使用Executors創建線程池,主要是避免使用其中的默認實現,那麼我們可以自己直接調用ThreadPoolExecutor的構造函數來自己創建線程池。在創建的同時,給BlockQueue指定容量就可以了。

private static ExecutorService executor = new ThreadPoolExecutor(10, 10,
        60L, TimeUnit.SECONDS,
        new ArrayBlockingQueue(10));

這種情況下,一旦提交的線程數超過當前可用線程數時,就會拋出java.util.concurrent.RejectedExecutionException,這是因爲當前線程池使用的隊列是有邊界隊列,隊列已經滿了便無法繼續處理新的請求。但是異常(Exception)總比發生錯誤(Error)要好。

除了自己定義ThreadPoolExecutor外。還有其他方法。這個時候第一時間就應該想到開源類庫,如apache和guava等。

作者推薦使用guava提供的ThreadFactoryBuilder來創建線程池。

public class ExecutorsDemo {

    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
        .setNameFormat("demo-pool-%d").build();

    private static ExecutorService pool = new ThreadPoolExecutor(5, 200,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {

        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            pool.execute(new SubThread());
        }
    }
}

通過上述方式創建線程時,不僅可以避免OOM的問題,還可以自定義線程名稱,更加方便的出錯的時候溯源。

參考資料

https://www.zhihu.com/question/23212914
https://www.zhihu.com/question/23212914/answer/245992718
https://www.jianshu.com/p/c41e942bcd64


Kotlin開發者社區

專注分享 Java、 Kotlin、Spring/Spring Boot、MySQL、redis、neo4j、NoSQL、Android、JavaScript、React、Node、函數式編程、編程思想、"高可用,高性能,高實時"大型分佈式系統架構設計主題。

High availability, high performance, high real-time large-scale distributed system architecture design

分佈式框架:Zookeeper、分佈式中間件框架等
分佈式存儲:GridFS、FastDFS、TFS、MemCache、redis等
分佈式數據庫:Cobar、tddl、Amoeba、Mycat
雲計算、大數據、AI算法
虛擬化、雲原生技術
分佈式計算框架:MapReduce、Hadoop、Storm、Flink等
分佈式通信機制:Dubbo、RPC調用、共享遠程數據、消息隊列等
消息隊列MQ:Kafka、MetaQ,RocketMQ
怎樣打造高可用系統:基於硬件、軟件中間件、系統架構等一些典型方案的實現:HAProxy、基於Corosync+Pacemaker的高可用集羣套件中間件系統
Mycat架構分佈式演進
大數據Join背後的難題:數據、網絡、內存和計算能力的矛盾和調和
Java分佈式系統中的高性能難題:AIO,NIO,Netty還是自己開發框架?
高性能事件派發機制:線程池模型、Disruptor模型等等。。。

合抱之木,生於毫末;九層之臺,起於壘土;千里之行,始於足下。不積跬步,無以至千里;不積小流,無以成江河。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章