摘要:原理剖析第篇工作原理分析一大致介紹相信大家都用過(guò)線(xiàn)程池,對(duì)該類(lèi)應(yīng)該一點(diǎn)都不陌生了我們之所以要用到線(xiàn)程池,線(xiàn)程池主要用來(lái)解決線(xiàn)程生命周期開(kāi)銷(xiāo)問(wèn)題和資源不足問(wèn)題我們通過(guò)對(duì)多個(gè)任務(wù)重用線(xiàn)程以及控制線(xiàn)程池的數(shù)目可以有效防止資源不足的情況本章節(jié)就著
原理剖析(第 003 篇)ThreadPoolExecutor工作原理分析
-
一、大致介紹1、相信大家都用過(guò)線(xiàn)程池,對(duì)該類(lèi)ThreadPoolExecutor應(yīng)該一點(diǎn)都不陌生了; 2、我們之所以要用到線(xiàn)程池,線(xiàn)程池主要用來(lái)解決線(xiàn)程生命周期開(kāi)銷(xiāo)問(wèn)題和資源不足問(wèn)題; 3、我們通過(guò)對(duì)多個(gè)任務(wù)重用線(xiàn)程以及控制線(xiàn)程池的數(shù)目可以有效防止資源不足的情況; 4、本章節(jié)就著重和大家分享分析一下JDK8的ThreadPoolExecutor核心類(lèi),看看線(xiàn)程池是如何工作的;二、基本字段方法介紹 2.1 構(gòu)造器
1、四個(gè)構(gòu)造器: // 構(gòu)造器一 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue2.2 成員變量字段workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } // 構(gòu)造器二 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); } // 構(gòu)造器三 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); } // 構(gòu)造器四 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; } 2、通過(guò)仔細(xì)查看構(gòu)造器代碼,發(fā)現(xiàn)最終都是調(diào)用構(gòu)造器四,緊接著賦值了一堆的字段,接下來(lái)我們先看看這些字段是什么含義;
1、corePoolSize:核心運(yùn)行的線(xiàn)程池?cái)?shù)量大小,當(dāng)線(xiàn)程數(shù)量超過(guò)該值時(shí),就需要將超過(guò)該數(shù)量值的線(xiàn)程放到等待隊(duì)列中; 2、maximumPoolSize:線(xiàn)程池最大能容納的線(xiàn)程數(shù)(該數(shù)量已經(jīng)包含了corePoolSize數(shù)量),當(dāng)線(xiàn)程數(shù)量超過(guò)該值時(shí),則會(huì)拒絕執(zhí)行處理策略; 3、workQueue:等待隊(duì)列,當(dāng)達(dá)到corePoolSize的時(shí)候,就將新加入的線(xiàn)程追加到workQueue該等待隊(duì)列中; 當(dāng)然BlockingQueue類(lèi)也是一個(gè)抽象類(lèi),也有很多子類(lèi)來(lái)實(shí)現(xiàn)不同的隊(duì)列等待; 一般來(lái)說(shuō),阻塞隊(duì)列有一下幾種,ArrayBlockingQueue;LinkedBlockingQueue/SynchronousQueue/ArrayBlockingQueue/ PriorityBlockingQueue使用較少,一般使用LinkedBlockingQueue和Synchronous。 4、keepAliveTime:表示線(xiàn)程沒(méi)有任務(wù)執(zhí)行時(shí)最多保持多久存活時(shí)間,默認(rèn)情況下當(dāng)線(xiàn)程數(shù)量大于corePoolSize后keepAliveTime才會(huì)起作用 并生效,一旦線(xiàn)程池的數(shù)量小于corePoolSize后keepAliveTime又不起作用了; 但是如果調(diào)用了allowCoreThreadTimeOut(boolean)方法,在線(xiàn)程池中的線(xiàn)程數(shù)不大于corePoolSize時(shí), keepAliveTime參數(shù)也會(huì)起作用,直到線(xiàn)程池中的線(xiàn)程數(shù)為0; 5、threadFactory:新創(chuàng)建線(xiàn)程出生的地方; 6、handler:拒絕執(zhí)行處理抽象類(lèi),就是說(shuō)當(dāng)線(xiàn)程池在一些場(chǎng)景中,不能處理新加入的線(xiàn)程任務(wù)時(shí),會(huì)通過(guò)該對(duì)象處理拒絕策略; 該對(duì)象RejectedExecutionHandler有四個(gè)實(shí)現(xiàn)類(lèi),即四種策略,讓我們有選擇性的在什么場(chǎng)景下該怎么使用拒絕策略; 策略一( CallerRunsPolicy ):只要線(xiàn)程池沒(méi)關(guān)閉,就直接用調(diào)用者所在線(xiàn)程來(lái)運(yùn)行任務(wù); 策略二( AbortPolicy ):默認(rèn)策略,直接拋出RejectedExecutionException異常; 策略三( DiscardPolicy ):執(zhí)行空操作,什么也不干,拒絕任務(wù)后也不做任何回應(yīng); 策略四( DiscardOldestPolicy ):將隊(duì)列中存活最久的那個(gè)未執(zhí)行的任務(wù)拋棄掉,然后將當(dāng)前新的線(xiàn)程放進(jìn)去; 7、largestPoolSize:變量記錄了線(xiàn)程池在整個(gè)生命周期中曾經(jīng)出現(xiàn)的最大線(xiàn)程個(gè)數(shù); 8、allowCoreThreadTimeOut:當(dāng)為true時(shí),和弦線(xiàn)程也有超時(shí)退出的概念一說(shuō);2.3 成員方法
1、AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); // 原子變量值,是一個(gè)復(fù)核類(lèi)型的成員變量,是一個(gè)原子整數(shù),借助高低位包裝了兩個(gè)概念: 2、int COUNT_BITS = Integer.SIZE - 3; // 偏移位數(shù),常量值29,之所以偏移29,目的是將32位的原子變量值ctl的高3位設(shè)置為線(xiàn)程池的狀態(tài),低29位作為線(xiàn)程池大小數(shù)量值; 3、int CAPACITY = (1 << COUNT_BITS) - 1; // 線(xiàn)程池的最大容量值; 4、線(xiàn)程池的狀態(tài),原子變量值ctl的高三位: int RUNNING = -1 << COUNT_BITS; // 接受新任務(wù),并處理隊(duì)列任務(wù) int SHUTDOWN = 0 << COUNT_BITS; // 不接受新任務(wù),但會(huì)處理隊(duì)列任務(wù) int STOP = 1 << COUNT_BITS; // 不接受新任務(wù),不會(huì)處理隊(duì)列任務(wù),而且會(huì)中斷正在處理過(guò)程中的任務(wù) int TIDYING = 2 << COUNT_BITS; // 所有的任務(wù)已結(jié)束,workerCount為0,線(xiàn)程過(guò)渡到TIDYING狀態(tài),將會(huì)執(zhí)行terminated()鉤子方法 int TERMINATED = 3 << COUNT_BITS; // terminated()方法已經(jīng)完成 5、HashSet2.4 成員方法workers = new HashSet (); // 存放工作線(xiàn)程的線(xiàn)程池;
1、public void execute(Runnable command) // 提交任務(wù),添加Runnable對(duì)象到線(xiàn)程池,由線(xiàn)程池調(diào)度執(zhí)行 2、private static int workerCountOf(int c) { return c & CAPACITY; } // c & 高3位為0,低29位為1的CAPACITY,用于獲取低29位的線(xiàn)程數(shù)量 3、private boolean addWorker(Runnable firstTask, boolean core) // 添加worker工作線(xiàn)程,根據(jù)邊界值來(lái)決定是否創(chuàng)建新的線(xiàn)程 4、private static boolean isRunning(int c) // c通常一般為ctl,ctl值小于0,則處于可以接受新任務(wù)狀態(tài) 5、final void reject(Runnable command) // 拒絕執(zhí)行任務(wù)方法,當(dāng)線(xiàn)程池在一些場(chǎng)景中,不能處理新加入的線(xiàn)程時(shí),會(huì)通過(guò)該對(duì)象處理拒絕策略; 6、final void runWorker(Worker w) // 該方法被Worker工作線(xiàn)程的run方法調(diào)用,真正核心處理Runable任務(wù)的方法 7、private static int runStateOf(int c) { return c & ~CAPACITY; } // c & 高3位為1,低29位為0的~CAPACITY,用于獲取高3位保存的線(xiàn)程池狀態(tài) 8、public void shutdown() // 不會(huì)立即終止線(xiàn)程池,而是要等所有任務(wù)緩存隊(duì)列中的任務(wù)都執(zhí)行完后才終止,但再也不會(huì)接受新的任務(wù) 9、public List三、源碼分析 3.1、executeshutdownNow() // 立即終止線(xiàn)程池,并嘗試打斷正在執(zhí)行的任務(wù),并且清空任務(wù)緩存隊(duì)列,返回尚未執(zhí)行的任務(wù) 10、private void processWorkerExit(Worker w, boolean completedAbruptly) // worker線(xiàn)程退出
1、execute源碼: /** * Executes the given task sometime in the future. The task * may execute in a new thread or in an existing pooled thread. * * If the task cannot be submitted for execution, either because this * executor has been shutdown or because its capacity has been reached, * the task is handled by the current {@code RejectedExecutionHandler}. * * @param command the task to execute * @throws RejectedExecutionException at discretion of * {@code RejectedExecutionHandler}, if the task * cannot be accepted for execution * @throws NullPointerException if {@code command} is null */ public void execute(Runnable command) { if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn"t, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); // 獲取原子計(jì)數(shù)值最新值 if (workerCountOf(c) < corePoolSize) { // 判斷當(dāng)前線(xiàn)程池?cái)?shù)量是否小于核心線(xiàn)程數(shù)量 if (addWorker(command, true)) // 嘗試添加command任務(wù)到核心線(xiàn)程 return; c = ctl.get(); // 重新獲取當(dāng)前線(xiàn)程池狀態(tài)值,為后面的檢查做準(zhǔn)備。 } // 執(zhí)行到此,說(shuō)明核心線(xiàn)程任務(wù)數(shù)量已滿(mǎn),新添加的線(xiàn)程入等待隊(duì)列,這個(gè)熟練是大于corePoolSize且小于maximumPoolSize if (isRunning(c) && workQueue.offer(command)) { // 如果線(xiàn)程池處于可接受任務(wù)狀態(tài),嘗試添加到等待隊(duì)列 int recheck = ctl.get(); // 雙重校驗(yàn) if (! isRunning(recheck) && remove(command)) // 如果線(xiàn)程池突然不可接受任務(wù),則嘗試移除該command任務(wù) reject(command); // 不可接受任務(wù)且成功從等待隊(duì)列移除任務(wù),則執(zhí)行拒絕策略操作,通過(guò)策略告訴調(diào)用方任務(wù)入隊(duì)情況 else if (workerCountOf(recheck) == 0) // 如果此刻線(xiàn)程數(shù)量為0的話(huà)將沒(méi)有Worker執(zhí)行新的task,所以增加一個(gè)Worker addWorker(null, false); // 添加一個(gè)Worker } // 執(zhí)行到此,說(shuō)明添加任務(wù)等待隊(duì)列已滿(mǎn),所以嘗試添加一個(gè)Worker else if (!addWorker(command, false)) // 如果添加失敗的話(huà),那么拒絕此線(xiàn)程任務(wù)添加 reject(command); // 拒絕此線(xiàn)程任務(wù)添加 } 2、小結(jié): ? 如果線(xiàn)程池中的線(xiàn)程數(shù)量 < corePoolSize,就創(chuàng)建新的線(xiàn)程來(lái)執(zhí)行新添加的任務(wù); ? 如果線(xiàn)程池中的線(xiàn)程數(shù)量 >= corePoolSize,但隊(duì)列workQueue未滿(mǎn),則將新添加的任務(wù)放到workQueue中; ? 如果線(xiàn)程池中的線(xiàn)程數(shù)量 >= corePoolSize,且隊(duì)列workQueue已滿(mǎn),但線(xiàn)程池中的線(xiàn)程數(shù)量 < maximumPoolSize,則會(huì)創(chuàng)建新的線(xiàn)程來(lái)處理被添加的任務(wù); ? 如果線(xiàn)程池中的線(xiàn)程數(shù)量 = maximumPoolSize,就用RejectedExecutionHandler來(lái)執(zhí)行拒絕策略;3.2、addWorker
1、addWorker源碼: /** * Checks if a new worker can be added with respect to current * pool state and the given bound (either core or maximum). If so, * the worker count is adjusted accordingly, and, if possible, a * new worker is created and started, running firstTask as its * first task. This method returns false if the pool is stopped or * eligible to shut down. It also returns false if the thread * factory fails to create a thread when asked. If the thread * creation fails, either due to the thread factory returning * null, or due to an exception (typically OutOfMemoryError in * Thread.start()), we roll back cleanly. * * @param firstTask the task the new thread should run first (or * null if none). Workers are created with an initial first task * (in method execute()) to bypass queuing when there are fewer * than corePoolSize threads (in which case we always start one), * or when the queue is full (in which case we must bypass queue). * Initially idle threads are usually created via * prestartCoreThread or to replace other dying workers. * * @param core if true use corePoolSize as bound, else * maximumPoolSize. (A boolean indicator is used here rather than a * value to ensure reads of fresh values after checking other pool * state). * @return true if successful */ private boolean addWorker(Runnable firstTask, boolean core) { retry: // 外層循環(huán),負(fù)責(zé)判斷線(xiàn)程池狀態(tài),處理線(xiàn)程池狀態(tài)變量加1操作 for (;;) { int c = ctl.get(); int rs = runStateOf(c); // 讀取狀態(tài)值 // Check if queue empty only if necessary. // 滿(mǎn)足下面兩大條件的,說(shuō)明線(xiàn)程池不能接受任務(wù)了,直接返回false處理 // 主要目的就是想說(shuō),只有線(xiàn)程池的狀態(tài)為 RUNNING 狀態(tài)時(shí),線(xiàn)程池才會(huì)接收新的任務(wù),增加新的Worker工作線(xiàn)程 if (rs >= SHUTDOWN && // 線(xiàn)程池的狀態(tài)已經(jīng)至少已經(jīng)處于不能接收任務(wù)的狀態(tài)了,目的是檢查線(xiàn)程池是否處于關(guān)閉狀態(tài) ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty())) return false; // 內(nèi)層循環(huán),負(fù)責(zé)worker數(shù)量加1操作 for (;;) { int wc = workerCountOf(c); // 獲取當(dāng)前worker線(xiàn)程數(shù)量 if (wc >= CAPACITY || // 如果線(xiàn)程池?cái)?shù)量達(dá)到最大上限值CAPACITY // core為true時(shí)判斷是否大于corePoolSize核心線(xiàn)程數(shù)量 // core為false時(shí)判斷是否大于maximumPoolSize最大設(shè)置的線(xiàn)程數(shù)量 wc >= (core ? corePoolSize : maximumPoolSize)) return false; // 調(diào)用CAS原子操作,目的是worker線(xiàn)程數(shù)量加1 if (compareAndIncrementWorkerCount(c)) // break retry; c = ctl.get(); // Re-read ctl // CAS原子操作失敗的話(huà),則再次讀取ctl值 if (runStateOf(c) != rs) // 如果剛剛讀取的c狀態(tài)不等于先前讀取的rs狀態(tài),則繼續(xù)外層循環(huán)判斷 continue retry; // else CAS failed due to workerCount change; retry inner loop // 之所以會(huì)CAS操作失敗,主要是由于多線(xiàn)程并發(fā)操作,導(dǎo)致workerCount工作線(xiàn)程數(shù)量改變而導(dǎo)致的,因此繼續(xù)內(nèi)層循環(huán)嘗試操作 } } boolean workerStarted = false; boolean workerAdded = false; Worker w = null; try { // 創(chuàng)建一個(gè)Worker工作線(xiàn)程對(duì)象,將任務(wù)firstTask,新創(chuàng)建的線(xiàn)程thread都封裝到了Worker對(duì)象里面 w = new Worker(firstTask); final Thread t = w.thread; if (t != null) { // 由于對(duì)工作線(xiàn)程集合workers的添加或者刪除,涉及到線(xiàn)程安全問(wèn)題,所以才加上鎖且該鎖為非公平鎖 final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. // 獲取鎖成功后,執(zhí)行臨界區(qū)代碼,首先檢查獲取當(dāng)前線(xiàn)程池的狀態(tài)rs int rs = runStateOf(ctl.get()); // 當(dāng)線(xiàn)程池處于可接收任務(wù)狀態(tài) // 或者是不可接收任務(wù)狀態(tài),但是有可能該任務(wù)等待隊(duì)列中的任務(wù) // 滿(mǎn)足這兩種條件時(shí),都可以添加新的工作線(xiàn)程 if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) { if (t.isAlive()) // precheck that t is startable throw new IllegalThreadStateException(); workers.add(w); // 添加新的工作線(xiàn)程到工作線(xiàn)程集合workers,workers是set集合 int s = workers.size(); if (s > largestPoolSize) // 變量記錄了線(xiàn)程池在整個(gè)生命周期中曾經(jīng)出現(xiàn)的最大線(xiàn)程個(gè)數(shù) largestPoolSize = s; workerAdded = true; } } finally { mainLock.unlock(); } if (workerAdded) { // 往workers工作線(xiàn)程集合中添加成功后,則立馬調(diào)用線(xiàn)程start方法啟動(dòng)起來(lái) t.start(); workerStarted = true; } } } finally { if (! workerStarted) // 如果啟動(dòng)線(xiàn)程失敗的話(huà),還得將剛剛添加成功的線(xiàn)程共集合中移除并且做線(xiàn)程數(shù)量做減1操作 addWorkerFailed(w); } return workerStarted; } 2、小結(jié): ? 該方法是任務(wù)提交的一個(gè)核心方法,主要完成狀態(tài)的檢查,工作線(xiàn)程的創(chuàng)建并添加到線(xiàn)程集合切最后順利的話(huà)將創(chuàng)建的線(xiàn)程啟動(dòng); ? addWorker(command, true):當(dāng)線(xiàn)程數(shù)小于corePoolSize時(shí),添加一個(gè)需要處理的任務(wù)command進(jìn)線(xiàn)程集合,如果workers數(shù)量超過(guò)corePoolSize時(shí),則返回false不需要添加工作線(xiàn)程; ? addWorker(command, false):當(dāng)?shù)却?duì)列已滿(mǎn)時(shí),將新來(lái)的任務(wù)command添加到workers線(xiàn)程集合中去,若線(xiàn)程集合大小超過(guò)maximumPoolSize時(shí),則返回false不需要添加工作線(xiàn)程; ? addWorker(null, false):放一個(gè)空的任務(wù)進(jìn)線(xiàn)程集合,當(dāng)這個(gè)空任務(wù)的線(xiàn)程執(zhí)行時(shí),會(huì)從等待任務(wù)隊(duì)列中通過(guò)getTask獲取任務(wù)再執(zhí)行,創(chuàng)建新線(xiàn)程且沒(méi)有任務(wù)分配,當(dāng)執(zhí)行時(shí)才去取任務(wù); ? addWorker(null, true):創(chuàng)建空任務(wù)的工作線(xiàn)程到workers集合中去,在setCorePoolSize方法調(diào)用時(shí)目的是初始化核心工作線(xiàn)程實(shí)例;3.3、runWorker
1、runWorker源碼: /** * Main worker run loop. Repeatedly gets tasks from queue and * executes them, while coping with a number of issues: * * 1. We may start out with an initial task, in which case we * don"t need to get the first one. Otherwise, as long as pool is * running, we get tasks from getTask. If it returns null then the * worker exits due to changed pool state or configuration * parameters. Other exits result from exception throws in * external code, in which case completedAbruptly holds, which * usually leads processWorkerExit to replace this thread. * * 2. Before running any task, the lock is acquired to prevent * other pool interrupts while the task is executing, and then we * ensure that unless pool is stopping, this thread does not have * its interrupt set. * * 3. Each task run is preceded by a call to beforeExecute, which * might throw an exception, in which case we cause thread to die * (breaking loop with completedAbruptly true) without processing * the task. * * 4. Assuming beforeExecute completes normally, we run the task, * gathering any of its thrown exceptions to send to afterExecute. * We separately handle RuntimeException, Error (both of which the * specs guarantee that we trap) and arbitrary Throwables. * Because we cannot rethrow Throwables within Runnable.run, we * wrap them within Errors on the way out (to the thread"s * UncaughtExceptionHandler). Any thrown exception also * conservatively causes thread to die. * * 5. After task.run completes, we call afterExecute, which may * also throw an exception, which will also cause thread to * die. According to JLS Sec 14.20, this exception is the one that * will be in effect even if task.run throws. * * The net effect of the exception mechanics is that afterExecute * and the thread"s UncaughtExceptionHandler have as accurate * information as we can provide about any problems encountered by * user code. * * @param w the worker */ final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts 允許中斷 boolean completedAbruptly = true; try { // 不斷從等待隊(duì)列blockingQueue中獲取任務(wù) // 之前addWorker(null, false)這樣的線(xiàn)程執(zhí)行時(shí),會(huì)通過(guò)getTask中再次獲取任務(wù)并執(zhí)行 while (task != null || (task = getTask()) != null) { w.lock(); // 上鎖,并不是防止并發(fā)執(zhí)行任務(wù),而是為了防止shutdown()被調(diào)用時(shí)不終止正在運(yùn)行的worker線(xiàn)程 // If pool is stopping, ensure thread is interrupted; // if not, ensure thread is not interrupted. This // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) wt.interrupt(); try { // task.run()執(zhí)行前,由子類(lèi)實(shí)現(xiàn) beforeExecute(wt, task); Throwable thrown = null; try { task.run(); // 執(zhí)行線(xiàn)程Runable的run方法 } catch (RuntimeException x) { thrown = x; throw x; } catch (Error x) { thrown = x; throw x; } catch (Throwable x) { thrown = x; throw new Error(x); } finally { // task.run()執(zhí)行后,由子類(lèi)實(shí)現(xiàn) afterExecute(task, thrown); } } finally { task = null; w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); } } 2、小結(jié): ? addWorker通過(guò)調(diào)用t.start()啟動(dòng)了線(xiàn)程,線(xiàn)程池的真正核心執(zhí)行任務(wù)的地方就在此runWorker中; ? 不斷的執(zhí)行我們提交任務(wù)的run方法,可能是剛剛提交的任務(wù),可能是隊(duì)列中等待的隊(duì)列,原因在于Worker工作線(xiàn)程類(lèi)繼承了AQS類(lèi); ? Worker重寫(xiě)了AQS的tryAcquire方法,不管先來(lái)后到,一種非公平的競(jìng)爭(zhēng)機(jī)制,通過(guò)CAS獲取鎖,獲取到了就執(zhí)行代碼塊,沒(méi)獲取到的話(huà)則添加到CLH隊(duì)列中通過(guò)利用LockSuporrt的park/unpark阻塞任務(wù)等待; ? addWorker通過(guò)調(diào)用t.start()啟動(dòng)了線(xiàn)程,線(xiàn)程池的真正核心執(zhí)行任務(wù)的地方就在此runWorker中;3.processWorkerExit
1、processWorkerExit源碼: /** * Performs cleanup and bookkeeping for a dying worker. Called * only from worker threads. Unless completedAbruptly is set, * assumes that workerCount has already been adjusted to account * for exit. This method removes thread from worker set, and * possibly terminates the pool or replaces the worker if either * it exited due to user task exception or if fewer than * corePoolSize workers are running or queue is non-empty but * there are no workers. * * @param w the worker * @param completedAbruptly if the worker died due to user exception */ private void processWorkerExit(Worker w, boolean completedAbruptly) { // 如果突然中止,說(shuō)明runWorker中遇到什么異常了,那么正在工作的線(xiàn)程自然就需要減1操作了 if (completedAbruptly) // If abrupt, then workerCount wasn"t adjusted decrementWorkerCount(); final ReentrantLock mainLock = this.mainLock; // 執(zhí)行到此,說(shuō)明runWorker正常執(zhí)行完了,需要正常退出工作線(xiàn)程,上鎖正常操作移除線(xiàn)程 mainLock.lock(); try { completedTaskCount += w.completedTasks; // 增加線(xiàn)程池完成任務(wù)數(shù) workers.remove(w); // 從workers線(xiàn)程集合中移除已經(jīng)工作完的線(xiàn)程 } finally { mainLock.unlock(); } // 在對(duì)線(xiàn)程池有負(fù)效益的操作時(shí),都需要“嘗試終止”線(xiàn)程池,主要是判斷線(xiàn)程池是否滿(mǎn)足終止的狀態(tài); // 如果狀態(tài)滿(mǎn)足,但還有線(xiàn)程池還有線(xiàn)程,嘗試對(duì)其發(fā)出中斷響應(yīng),使其能進(jìn)入退出流程; // 沒(méi)有線(xiàn)程了,更新?tīng)顟B(tài)為tidying->terminated; tryTerminate(); int c = ctl.get(); // 如果狀態(tài)是running、shutdown,即tryTerminate()沒(méi)有成功終止線(xiàn)程池,嘗試再添加一個(gè)worker if (runStateLessThan(c, STOP)) { // 不是突然完成的,即沒(méi)有task任務(wù)可以獲取而完成的,計(jì)算min,并根據(jù)當(dāng)前worker數(shù)量判斷是否需要addWorker() if (!completedAbruptly) { int min = allowCoreThreadTimeOut ? 0 : corePoolSize; // 如果min為0,且workQueue不為空,至少保持一個(gè)線(xiàn)程 if (min == 0 && ! workQueue.isEmpty()) min = 1; // 如果線(xiàn)程數(shù)量大于最少數(shù)量,直接返回,否則下面至少要addWorker一個(gè) if (workerCountOf(c) >= min) return; // replacement not needed } // 只要worker是completedAbruptly突然終止的,或者線(xiàn)程數(shù)量小于要維護(hù)的數(shù)量,就新添一個(gè)worker線(xiàn)程,即使是shutdown狀態(tài) addWorker(null, false); } } 2、小結(jié): ? 異常中止情況worker數(shù)量減1,正常情況就上鎖從workers中移除; ? tryTerminate():在對(duì)線(xiàn)程池有負(fù)效益的操作時(shí),都需要“嘗試終止”線(xiàn)程池; ? 是否需要增加worker線(xiàn)程,如果線(xiàn)程池還沒(méi)有完全終止,仍需要保持一定數(shù)量的線(xiàn)程;四、一些建議 4.1、合理配置線(xiàn)程池的大小(僅供參考)
1、如果是CPU密集型任務(wù),就需要盡量壓榨CPU,參考值可以設(shè)為 NCPU+1; 2、如果是IO密集型任務(wù),參考值可以設(shè)置為2*NCPU;4.2、JDK幫助文檔建議
“強(qiáng)烈建議程序員使用較為方便的Executors工廠(chǎng)方法:五、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接
歡迎關(guān)注,您的肯定是對(duì)我最大的支持!!!
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/68764.html
摘要:原理剖析第篇工作原理分析一大致介紹關(guān)于多線(xiàn)程競(jìng)爭(zhēng)鎖方面,大家都知道有個(gè)和,也正是這兩個(gè)東西才引申出了大量的線(xiàn)程安全類(lèi),鎖類(lèi)等功能而隨著現(xiàn)在的硬件廠(chǎng)商越來(lái)越高級(jí),在硬件層面提供大量并發(fā)原語(yǔ)給我們層面的開(kāi)發(fā)帶來(lái)了莫大的利好本章節(jié)就和大家分享分 原理剖析(第 004 篇)CAS工作原理分析 - 一、大致介紹 1、關(guān)于多線(xiàn)程競(jìng)爭(zhēng)鎖方面,大家都知道有個(gè)CAS和AQS,也正是這兩個(gè)東西才引申出了大...
摘要:表示的是兩個(gè),當(dāng)其中任意一個(gè)計(jì)算完并發(fā)編程之是線(xiàn)程安全并且高效的,在并發(fā)編程中經(jīng)常可見(jiàn)它的使用,在開(kāi)始分析它的高并發(fā)實(shí)現(xiàn)機(jī)制前,先講講廢話(huà),看看它是如何被引入的。電商秒殺和搶購(gòu),是兩個(gè)比較典型的互聯(lián)網(wǎng)高并發(fā)場(chǎng)景。 干貨:深度剖析分布式搜索引擎設(shè)計(jì) 分布式,高可用,和機(jī)器學(xué)習(xí)一樣,最近幾年被提及得最多的名詞,聽(tīng)名字多牛逼,來(lái),我們一步一步來(lái)?yè)羝魄皟蓚€(gè)名詞,今天我們首先來(lái)說(shuō)說(shuō)分布式。 探究...
摘要:表示的是兩個(gè),當(dāng)其中任意一個(gè)計(jì)算完并發(fā)編程之是線(xiàn)程安全并且高效的,在并發(fā)編程中經(jīng)常可見(jiàn)它的使用,在開(kāi)始分析它的高并發(fā)實(shí)現(xiàn)機(jī)制前,先講講廢話(huà),看看它是如何被引入的。電商秒殺和搶購(gòu),是兩個(gè)比較典型的互聯(lián)網(wǎng)高并發(fā)場(chǎng)景。 干貨:深度剖析分布式搜索引擎設(shè)計(jì) 分布式,高可用,和機(jī)器學(xué)習(xí)一樣,最近幾年被提及得最多的名詞,聽(tīng)名字多牛逼,來(lái),我們一步一步來(lái)?yè)羝魄皟蓚€(gè)名詞,今天我們首先來(lái)說(shuō)說(shuō)分布式。 探究...
摘要:表示的是兩個(gè),當(dāng)其中任意一個(gè)計(jì)算完并發(fā)編程之是線(xiàn)程安全并且高效的,在并發(fā)編程中經(jīng)常可見(jiàn)它的使用,在開(kāi)始分析它的高并發(fā)實(shí)現(xiàn)機(jī)制前,先講講廢話(huà),看看它是如何被引入的。電商秒殺和搶購(gòu),是兩個(gè)比較典型的互聯(lián)網(wǎng)高并發(fā)場(chǎng)景。 干貨:深度剖析分布式搜索引擎設(shè)計(jì) 分布式,高可用,和機(jī)器學(xué)習(xí)一樣,最近幾年被提及得最多的名詞,聽(tīng)名字多牛逼,來(lái),我們一步一步來(lái)?yè)羝魄皟蓚€(gè)名詞,今天我們首先來(lái)說(shuō)說(shuō)分布式。 探究...
摘要:原理剖析第篇之服務(wù)端啟動(dòng)工作原理分析下一大致介紹由于篇幅過(guò)長(zhǎng)難以發(fā)布,所以本章節(jié)接著上一節(jié)來(lái)的,上一章節(jié)為原理剖析第篇之服務(wù)端啟動(dòng)工作原理分析上那么本章節(jié)就繼續(xù)分析的服務(wù)端啟動(dòng),分析的源碼版本為二三四章節(jié)請(qǐng)看上一章節(jié)詳見(jiàn)原理剖析第篇之 原理剖析(第 011 篇)Netty之服務(wù)端啟動(dòng)工作原理分析(下) - 一、大致介紹 1、由于篇幅過(guò)長(zhǎng)難以發(fā)布,所以本章節(jié)接著上一節(jié)來(lái)的,上一章節(jié)為【原...
閱讀 2670·2021-11-11 16:54
閱讀 3667·2021-08-16 10:46
閱讀 3447·2019-08-30 14:18
閱讀 3040·2019-08-30 14:01
閱讀 2729·2019-08-29 14:15
閱讀 2012·2019-08-29 11:31
閱讀 3090·2019-08-29 11:05
閱讀 2593·2019-08-26 11:54