java并發:線程池之飽和策略
一、飽和策略(線程池任務拒絕策略)
ThreadPoolExecutor構造函數的RejectedExecutionHandler handler參數表示當提交的任務數超過maxmumPoolSize與workQueue之和時,任務會交給RejectedExecutionHandler來處理,此處我們來具體了解一下



二、源碼分析
(1)ThreadPoolExecutor中默認的飽和策略定義如下:
/** * The default rejected execution handler. */ private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();
(2)ThreadPoolExecutor中獲取、設置飽和策略的方法如下:
/** * Sets a new handler for unexecutable tasks. * * @param handler the new handler * @throws NullPointerException if handler is null * @see #getRejectedExecutionHandler */ public void setRejectedExecutionHandler(RejectedExecutionHandler handler) { if (handler == null) throw new NullPointerException(); this.handler = handler; } /** * Returns the current handler for unexecutable tasks. * * @return the current handler * @see #setRejectedExecutionHandler(RejectedExecutionHandler) */ public RejectedExecutionHandler getRejectedExecutionHandler() { return handler; }
(3)RejectedExecutionHandler接口
RejectedExecutionHandler的定義如下:
public interface RejectedExecutionHandler{ //被線程池丟棄的線程處理機制 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) ; }
(4)AbortPolicy
此策略繼承RejectedExecutionHandler接口,其源碼如下:
public static class AbortPolicy implements RejectedExecutionHandler{ public AbortPolicy(){} //直接拋出異常 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { throw new RejectedExecutionException("Task"+r.toString()+"rejected from"+executor.toString()); } }
(5)自定義飽和策略
實現RejectedExecutionHandler接口,代碼如下:
package com.test; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public class RejectedExecutionHandlerDemo implements RejectedExecutionHandler{ @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { // TODO Auto-generated method stub System.out.println("線程信息"+r.toString()+"被遺棄的線程池:"+executor.toString()); } }
Note:
針對線程池使用 FutureTask 時,如果飽和策略設置為 DiscardPolicy 和 DiscardOldestPolicy,并且在被拒絕的任務的 Future對象上調用了無參 get方法,那么調用線程會一直被阻塞。

浙公網安備 33010602011771號