1. 程式人生 > >為什麼不推薦通過Executors直接建立執行緒池

為什麼不推薦通過Executors直接建立執行緒池

通過Executors的方法創建出來的執行緒池都實現了ExecutorSerivice介面。常用的方法有

newFixedThreadPool(int Threads):建立固定數目的執行緒池。
newSingleThreadPoolExecutor():建立一個單執行緒化的Executor
newCacheThreadPool():建立一個可快取的執行緒池,呼叫execute將重用以前構成的執行緒(如果執行緒可用)。如果沒有可用的執行緒,則建立一個新執行緒並新增到池中。終止並從快取中移出那些已有60秒鐘未被使用的執行緒。
newScheduledThreadPool(int corePoolSize)建立一個支援定時及週期性的任務執行的執行緒池,多數情況下可用來替代Time類。

但是在阿里巴巴java開發手冊中明確指出,不允許使用Executors建立執行緒池。

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
        }
    }
}

原因

:java中BlockingQueue主要有兩種實現,分別是ArrayBlockingQueue和LinkedBlockingQueue。ArrayBlockingQueue是一個用陣列實現的有界阻塞佇列,必須設定容量。而LinkedBlockingQueue是一個用連結串列實現的有界阻塞佇列,容量可以選擇進行設定,不設定的話,將是一個無邊界的阻塞佇列,最大長度為Integer.MAX_VALUE.

檢視new SingleExecutor時的原始碼可以發現,在建立LinkedBlockingQueue時,並未指定容量。此時,LinkedBlockingQueue就是一個無邊界佇列,對於一個無邊界佇列來說,是可以不斷的向佇列中加入任務的,這種情況下就有可能因為任務過多而導致記憶體溢位的問題。

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }


ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue)

建立執行緒池的正確方法:

避免使用Executors建立執行緒池,主要是避免使用其中的預設實現,那麼我們可以自己直接呼叫ThreadPoolExecutor的建構函式自己建立執行緒池。在建立的同時,給BlockQueue指定容量就可以了。

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

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

Java中執行緒池,你真的會用嗎

https://blog.csdn.net/hollis_chuang/article/details/83743723