Tomcat JDBC pool源碼部析 (2)

上一篇主要分析了獲取連接,本篇分析歸還連接與連接清理。歸還連接基本上就一個入口:

  1. protected void returnConnection(PooledConnection con) { 
  2.        if (isClosed()) { 
  3.            //if the connection pool is closed 
  4.            //close the connection instead of returning it 
  5.            release(con); 
  6.            return
  7.        } //end if 
  8.  
  9.        if (con != null) { 
  10.            try { 
  11.                con.lock(); 
  12.  
  13.                if (busy.remove(con)) { 
  14.  
  15.                    if (!shouldClose(con,PooledConnection.VALIDATE_RETURN)) { 
  16.                        con.setStackTrace(null); 
  17.                        con.setTimestamp(System.currentTimeMillis()); 
  18.                        if (((idle.size()>=poolProperties.getMaxIdle()) && !poolProperties.isPoolSweeperEnabled()) || (!idle.offer(con))) { 
  19.                            if (log.isDebugEnabled()) { 
  20.                                log.debug("Connection ["+con+"] will be closed and not returned to the pool, idle["+idle.size()+"]>=maxIdle["+poolProperties.getMaxIdle()+"] idle.offer failed."); 
  21.                            } 
  22.                            release(con); 
  23.                        } 
  24.                    } else { 
  25.                        if (log.isDebugEnabled()) { 
  26.                            log.debug("Connection ["+con+"] will be closed and not returned to the pool."); 
  27.                        } 
  28.                        release(con); 
  29.                    } //end if 
  30.                } else { 
  31.                    if (log.isDebugEnabled()) { 
  32.                        log.debug("Connection ["+con+"] will be closed and not returned to the pool, busy.remove failed."); 
  33.                    } 
  34.                    release(con); 
  35.                } 
  36.            } finally { 
  37.                con.unlock(); 
  38.            } 
  39.        } //end if 
  40.    } // 

先看連接池有沒有關閉,如果在關閉狀態,則調用release(con)關閉該連接。

獲取當前連接的鎖,從繁忙隊列中移除該連接。放入空閒隊列中以備其他請求使用。有以下幾種情況,該連接會直接關閉,而非放入空閒隊列。

1.     從繁忙隊列中移除該連接時失敗。(此現象很少見)

2.     空閒連接數大小允許的最大空閒連接數,且沒有啓用空閒連接清理器。

3.     放入空閒隊列失敗。(與1比較類似,比較少見)

可以看出歸還連接比較簡單。

對於連接清理,連接池提供了一個Timer來完成:

class PoolCleaner extends TimerTask

Timer主要清理三個方面的連接。

1.     需要丟棄的連接,從繁忙隊列清除。

這類連接主要是長期沒有歸還的連接。連接池提供了兩個時間值:AbandonTimeoutSuspectTimeout。對於超過AbandonTimeout連接,如果Pool當前符合清理Abandon連接的條件,則執行關閉。

對於大於的SuspectTimeout的連接,輸出日誌提醒。

2.     空閒的連接,從空閒隊列中清除。

關閉空閒時間過長的連接,沒什麼好說的。

3.     對空閒連接進行驗證(如果),驗證失敗的連接。

   VALIDATE_IDLE驗證方式是用戶指定的用於以空閒連接進行驗證策略,意議不大。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章