重寫并優(yōu)化 ThreadPoolExecutor 線程池

import java.util.concurrent.*;

import java.util.concurrent.atomic.AtomicInteger;

/**

* Created by yehan .

*? 代碼和思路主要來自于:

*

* tomcat :

*? ? ? ? org.apache.catalina.core.StandardThreadExecutor

*

* java.util.concurrent

* threadPoolExecutor execute執(zhí)行策略:? ? ? ? 優(yōu)先offer到queue蜒程,queue滿后再擴充線程到maxThread相寇,如果已經(jīng)到了maxThread就reject

*? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 比較適合于CPU密集型應用(比如runnable內(nèi)部執(zhí)行的操作都在JVM內(nèi)部因俐,memory copy, or compute等等)

*

* StandardThreadExecutor execute執(zhí)行策略: 優(yōu)先擴充線程到maxThread候齿,再offer到queue竹观,如果滿了就reject

*? ? ? ? ? ? ? ? ? ? ? ? ? 比較適合于業(yè)務處理需要遠程資源的場景

*

* @author yehan

*

*/

public class StandardThreadExecutorextends ThreadPoolExecutor {

public static final int DEFAULT_MIN_THREADS =20;

? ? public static final int DEFAULT_MAX_THREADS =200;

? ? /**1 minutes*/

? ? public static final int DEFAULT_MAX_IDLE_TIME =60 *1000;

? ? /**正在處理的任務數(shù)*/

? ? protected AtomicIntegersubmittedTasksCount;

? ? /**最大允許同時處理的任務數(shù)*/

? ? private int maxSubmittedTaskCount;

? ? public StandardThreadExecutor() {

this(DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS);

? ? }

public StandardThreadExecutor(int coreThread, int maxThreads) {

this(coreThread, maxThreads, maxThreads);

? ? }

public StandardThreadExecutor(int coreThread, int maxThreads, long keepAliveTime, TimeUnit unit) {

this(coreThread, maxThreads, keepAliveTime, unit, maxThreads);

? ? }

public StandardThreadExecutor(int coreThreads, int maxThreads, int queueCapacity) {

this(coreThreads, maxThreads, queueCapacity, Executors.defaultThreadFactory());

? ? }

public StandardThreadExecutor(int coreThreads, int maxThreads, int queueCapacity, ThreadFactory threadFactory) {

this(coreThreads, maxThreads, DEFAULT_MAX_IDLE_TIME, TimeUnit.MILLISECONDS, queueCapacity, threadFactory);

? ? }

public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit, int queueCapacity) {

this(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, Executors.defaultThreadFactory());

? ? }

public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? int queueCapacity, ThreadFactory threadFactory) {

this(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, threadFactory, new AbortPolicy());

? ? }

public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? int queueCapacity, ThreadFactory threadFactory, RejectedExecutionHandler handler) {

super(coreThreads, maxThreads, keepAliveTime, unit, new ExecutorQueue(), threadFactory, handler);

? ? ? ? ((ExecutorQueue) getQueue()).setStandardThreadExecutor(this);

? ? ? ? submittedTasksCount =new AtomicInteger(0);

? ? ? ? // 最大并發(fā)任務限制: 隊列buffer數(shù) + 最大線程數(shù)

? ? ? ? maxSubmittedTaskCount = queueCapacity + maxThreads;

? ? }

@Override

? ? public void execute(Runnable command) {

int count =submittedTasksCount.incrementAndGet();

? ? ? ? // 超過最大的并發(fā)任務限制,進行 reject

// 依賴的LinkedTransferQueue沒有長度限制,因此這里進行控制

? ? ? ? if (count >maxSubmittedTaskCount) {

submittedTasksCount.decrementAndGet();

? ? ? ? ? ? getRejectedExecutionHandler().rejectedExecution(command, this);

? ? ? ? }

try {

super.execute(command);

? ? ? ? }catch (RejectedExecutionException rx) {

// there could have been contention around the queue

? ? ? ? ? ? if (!((ExecutorQueue) getQueue()).force(command)) {

submittedTasksCount.decrementAndGet();

? ? ? ? ? ? ? ? getRejectedExecutionHandler().rejectedExecution(command, this);

? ? ? ? ? ? }

}

}

public int getSubmittedTasksCount() {

return this.submittedTasksCount.get();

? ? }

public int getMaxSubmittedTaskCount() {

return maxSubmittedTaskCount;

? ? }

@Override

? ? protected void afterExecute(Runnable r, Throwable t) {

submittedTasksCount.decrementAndGet();

? ? }

}

/**

* LinkedTransferQueue 能保證更高性能晒哄,相比與LinkedBlockingQueue有明顯提升

*

*


*? ? ? ? 1) 不過LinkedTransferQueue的缺點是沒有隊列長度控制购啄,需要在外層協(xié)助控制

*

*

* @author yehan

*

*/

class ExecutorQueueextends LinkedTransferQueue {

private static final long serialVersionUID = -265236426751004839L;

? ? StandardThreadExecutorthreadPoolExecutor;

? ? public ExecutorQueue() {

super();

? ? }

public void setStandardThreadExecutor(StandardThreadExecutor threadPoolExecutor) {

this.threadPoolExecutor = threadPoolExecutor;

? ? }

/** 注:代碼來源于 tomcat*/

? ? public boolean force(Runnable o) {

if (threadPoolExecutor.isShutdown()) {

throw new RejectedExecutionException("Executor not running, can't force a command into the queue");

? ? ? ? }

// forces the item onto the queue, to be used if the task is rejected

? ? ? ? return super.offer(o);

? ? }

/**

*注:tomcat的代碼進行一些小變更

*

*/

? ? @Override

? ? public boolean offer(Runnable o) {

int poolSize =threadPoolExecutor.getPoolSize();

? ? ? ? // we are maxed out on threads, simply queue the object

? ? ? ? if (poolSize ==threadPoolExecutor.getMaximumPoolSize()) {

return super.offer(o);

? ? ? ? }

// we have idle threads, just add it to the queue

// note that we don't use getActiveCount(), see BZ 49730

? ? ? ? if (threadPoolExecutor.getSubmittedTasksCount() <= poolSize) {

return super.offer(o);

? ? ? ? }

// if we have less threads than maximum force creation of a new

// thread

? ? ? ? if (poolSize

return false;

? ? ? ? }

// if we reached here, we need to add it to the queue

? ? ? ? return super.offer(o);

? ? }

}

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末襟企,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子狮含,更是在濱河造成了極大的恐慌顽悼,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件几迄,死亡現(xiàn)場離奇詭異蔚龙,居然都是意外死亡,警方通過查閱死者的電腦和手機映胁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進店門木羹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人解孙,你說我怎么就攤上這事坑填。” “怎么了弛姜?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵脐瑰,是天一觀的道長。 經(jīng)常有香客問我娱据,道長蚪黑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任中剩,我火速辦了婚禮忌穿,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘结啼。我一直安慰自己掠剑,他們只是感情好,可當我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布郊愧。 她就那樣靜靜地躺著朴译,像睡著了一般。 火紅的嫁衣襯著肌膚如雪属铁。 梳的紋絲不亂的頭發(fā)上眠寿,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天,我揣著相機與錄音焦蘑,去河邊找鬼盯拱。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的狡逢。 我是一名探鬼主播宁舰,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼奢浑!你這毒婦竟也來了蛮艰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤雀彼,失蹤者是張志新(化名)和其女友劉穎壤蚜,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體徊哑,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡仍律,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了实柠。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡善涨,死狀恐怖窒盐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情钢拧,我是刑警寧澤蟹漓,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站源内,受9級特大地震影響葡粒,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜膜钓,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一嗽交、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧颂斜,春花似錦夫壁、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至司蔬,卻和暖如春邑茄,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背俊啼。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工肺缕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓搓谆,卻偏偏與公主長得像炒辉,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子泉手,可洞房花燭夜當晚...
    茶點故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容