Java線程池實現原理

參數配置

核心池大小、最大池大小

 /**
     * Core pool size is the minimum number of workers to keep alive
     * (and not allow to time out etc) unless allowCoreThreadTimeOut
     * is set, in which case the minimum is zero.
     */
    private volatile int corePoolSize;

    /**
     * Maximum pool size. Note that the actual maximum is internally
     * bounded by CAPACITY.
     */
        private volatile int maximumPoolSize;
 /**
     * Timeout in nanoseconds for idle threads waiting for work.
     * Threads use this timeout when there are more than corePoolSize
     * present or if allowCoreThreadTimeOut. Otherwise they wait
     * forever for new work.
     */
    private volatile long keepAliveTime;

    /**
     * If false (default), core threads stay alive even when idle.
     * If true, core threads use keepAliveTime to time out waiting
     * for work.
     */
    private volatile boolean allowCoreThreadTimeOut;

ThreadPoolExecutor根據這兩個參數自動分配池大小。當線程數>corePoolSize 時,多於corePoolSize 的線程在超過keepAliveTime時間後,會終止執行。
另外如果設置了allowCoreThreadTimeOut爲true,核心線程在空閒時間超過keepAliveTime 後終止執行。

線程分配流程:

  • If fewer than corePoolSize threads are running, the Executor
  • always prefers adding a new thread
  • rather than queuing.
  • If corePoolSize or more threads are running, the Executor
  • always prefers queuing a request rather than adding a new
  • thread.
  • If a request cannot be queued, a new thread is created *unless this would exceed maximumPoolSize, in which case, the *task will be
  • rejected.

  1. 如果有新請求提交到線程池,且運行中的線程數<corePoolSize,新建一個線程處理請求(即使有工作線程處於空閒狀態)。

  2. 如果corePoolSize<=運行線程數,請求被放入隊列。

  3. 如果corePoolSize<運行線程<maximumPoolSize,除非隊列已滿,纔會新建一個線程處理請求。

  4. 如果運行線程達到maximumPoolSize且隊列已滿,將會執行rejectedExecution方法。

執行過程示意圖

這裏寫圖片描述

隊列實現策略

  1. SynchronousQueue:如果線程池中沒有可用線程,將會創建一個新的線程。maximumPoolSize無限大,以防止提交的任務達到maximumPoolSize大小後被拒絕執行。

  2. LinkedBlockingQueue:基於鏈表結構的阻塞隊列,如果corePoolSize全部線程用完,在隊列中等待,不會創建新線程,適合彼此獨立的任務。

  3. ArrayBlockingQueue:配合有限的maximumPoolSizes,防止資源用盡,但難以協調控制。隊列的大小和maximumPoolSizes需要權衡。

線程池的飽和策略

1.AbortPolicy
默認實現,直接拋出異常

    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

2.CallerRunsPolicy
executor調用線程直接執行被拒絕的任務(Runnable),除非調用線程executor被關閉,此時任務被丟棄。

 /**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

3.DiscardPolicy
直接丟棄被拒絕的任務,不做任何處理.

  /**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public DiscardPolicy() { }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }

4.DiscardOldestPolicy
從隊列中丟棄被拒絕的請求,executor調用線程執行被拒絕的任務(Runnable),除非調用線程executor被關閉,此時任務被丟棄。

 /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章