首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Tomcat 線程池源碼深度剖析(二):ControlRunnable 與 TCP 連接處理

     編輯:Java 相關知識

ControlRunnable 核心邏輯

runIt(ThreadPoolRunnable toRun)

僅被調用一次,不直接執行任務,而是設定 shouldRun=true 並 notify() 喚醒 run() 循環中的執行緒。

run() 方法:執行緒生命週期管理

while (true) {
    synchronized(this) {
        if (!shouldRun && !shouldTerminate) wait();
    }
    if (shouldTerminate) break;
    try {
        if (noThData) { // 首次初始化線程數據
            if (toRun != null) {
                Object[] thData = toRun.getInitData();
                t.setThreadData(p, thData);
            }
            noThData = false;
        }
        if (shouldRun) {
            if (toRun != null) toRun.runIt(t.getThreadData(p));
            else if (toRunRunnable != null) toRunRunnable.run();
        }
    } catch (Throwable t) {
        shouldTerminate = true; shouldRun = false;
        p.notifyThreadEnd(this);
    } finally {
        if (shouldRun) { shouldRun = false; p.returnController(this); }
    }
    if (shouldTerminate) break;
}

關鍵點:getInitData() 提供線程初始化數據,runIt(Object[]) 承載實際業務邏輯;異常導致線程終止並從池移除;finally 確保線程歸還池中。

輔助介面與類

  • ThreadPoolListener (Observer 模式):threadStart()/threadEnd() 監聽線程創建銷毀。
  • ThreadWithAttributes:攜帶控制對象與 Runnable 構造,提供類 ThreadLocal 但效率更高的線程屬性存儲(setNote/getNote),透過 control 物件防止非信任代碼篡改。
  • ThreadPoolRunnable:外部任務必須實作介面,含 getInitData()、runIt(Object[]) 兩方法。

TCP 連接處理實戰:PoolTcpEndpoint 與 TcpWorkerThread

PoolTcpEndpoint

  • initEndpoint():建立 ServerSocket(默認 8080),設定超時。
  • startEndpoint():啟動線程池,創建 TcpWorkerThread 監聽線程,tp.runIt(listener) 投遞任務。

TcpWorkerThread (實作 ThreadPoolRunnable)

  • 構造函數:預創建 TcpConnection 緩存(SimplePool)。
  • getInitData():返回 HTTP 處理器初始化數據及連接對象。
  • runIt(Object[]) 核心流程:
    1. acceptSocket() 阻塞等待連接。
    2. 連接建立後,立即啟動下一個監聽線程(endpoint.tp.runIt(this)),實現「一線程一連接、接力監聽」。
    3. SSL 握手(如需)。
    4. 從緩存或初始化數據取得 TcpConnection,設定 Socket 選項。
    5. 委派 ConnectionHandler.processConnection() 解析 Socket 流為 Request 對象,交由容器處理。
    6. finally 回收 TcpConnection 至緩存。

設計精髓總結

  1. 線程池僅管線程生命週期,業務邏輯外部化(ThreadPoolRunnable)。
  2. 面向組件編程(COP)思想貫穿:ControlRunnable、ThreadWithAttributes、ThreadPoolListener 解耦管理與業務。
  3. TCP 層採用「單線程接力監聽」而非固定線程池監聽,極大降低併發下的線程開銷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved