apache-commons-pool-1.5.4 源碼解析

前言

Apache-Commons-DBCP是數(shù)據(jù)庫(kù)連接池中一款優(yōu)秀的產(chǎn)品,熟悉dbcp同學(xué)都知道师坎,dbcp底層“池”的底層實(shí)現(xiàn)恕酸,是依賴Commos-Pool完成的,所以胯陋,在全面深入的掌握dbcp之前蕊温,學(xué)習(xí)一下commons-pool的我認(rèn)為是非常必要的。網(wǎng)絡(luò)上關(guān)于這類工具包的教程并不多遏乔,因此义矛,我只能從源碼入手,來(lái)“一探究竟”了盟萨。
這里選擇的版本為1.5.4凉翻,與dbcp-1.4版本中依賴的pool保持一致。

org.apache.commons.pool包

Commons-Pool的包結(jié)構(gòu)很接單捻激,僅有兩個(gè)包組成制轰,org.apache.commons.pool包內(nèi)主要是接口和抽象類,org.apache.commons.pool.impl包則是由org.apache.commons.pool包的實(shí)現(xiàn)類組成胞谭。
org.apache.commons.pool包內(nèi)有6個(gè)接口垃杖、4個(gè)抽象類和1個(gè)工具類組成:

  • 接口

    • KeyedObjectPool
    • KeyedObjectPoolFactory
    • KeyedPoolableObjectFactory
    • ObjectPool
    • ObjectPoolFactory
    • PoolableObjectFactory
  • 抽象類

    • BaseKeyedObjectPool
    • BaseKeyedPoolableObjectFactory
    • BaseObjectPool
    • BasePoolableObjectFactory
  • 工具類

    • PoolUtils

其中最核心的三個(gè)接口為:ObjectPool、PoolableObjectFactory和ObjectPoolFactory丈屹。

ObjectPool

ObjectPool就是一個(gè)對(duì)象池调俘,它主要描述一個(gè)“池”應(yīng)該提供的那些功能,主要方法有:

  • void addObject():向池里添加一個(gè)對(duì)象旺垒。
  • Object borrowObject():從池里獲取對(duì)象彩库。
  • void returnObject(Object obj):將對(duì)象交還給池。
  • boolean validateObject(Object obj):校驗(yàn)交還到池中的對(duì)象是否合法先蒋。

上述三個(gè)方法骇钦,是“池”這個(gè)設(shè)計(jì)思想的核心。

PoolableObjectFactory

PoolableObjectFactory是對(duì)ObjectPool的補(bǔ)充竞漾,它的著眼點(diǎn)在池中的“對(duì)象”司忱,它提供的主要方法有:

  • Object makeObject():創(chuàng)建一個(gè)對(duì)象皇忿。
  • void destroyObject(Object obj):銷毀一個(gè)對(duì)象

通常情況下,PoolableObjectFactory與ObjectPool是結(jié)對(duì)出現(xiàn)的坦仍。一個(gè)ObjectPool必然對(duì)應(yīng)一個(gè)PoolableObjectFactory。舉兩個(gè)簡(jiǎn)單的場(chǎng)景叨襟,當(dāng)對(duì)象池初始化時(shí)(addObject)繁扎,此時(shí)ObjectPool就會(huì)調(diào)用PoolableObjectFactory的makeObject方法,創(chuàng)建一個(gè)對(duì)象糊闽,并將對(duì)象蓄到池中梳玫;當(dāng)將對(duì)象交還給池時(shí)(returnObject),ObjectPool會(huì)首先調(diào)用PoolableObjectFactory的validateObject方法右犹,判斷當(dāng)前對(duì)象是否合法提澎,然后根據(jù)判斷結(jié)果選擇是否銷毀它(調(diào)用destroyObject方法)。

ObjectPoolFactory

ObjectPoolFactory就是一個(gè)創(chuàng)建對(duì)象池的工廠類念链。
由此盼忌,也基本可以梳理出來(lái),commons-pool具體的使用邏輯了掂墓。首先谦纱,我們需要定義個(gè)ObjectPoolFactory對(duì)象,由它來(lái)創(chuàng)建對(duì)象池君编,對(duì)象池其本質(zhì)就是一個(gè)Java對(duì)象跨嘉,所以理論上是可以創(chuàng)建多個(gè)。拿到對(duì)象池之后吃嘿,就可以正常使用了祠乃,但在這之前要給這個(gè)對(duì)象池提供一個(gè)PoolableObjectFactory,由它來(lái)完成具體對(duì)象的創(chuàng)建和回收兑燥,這么做的目的亮瓷,是為了保證對(duì)象池的“純凈”,也就是說(shuō)贪嫂,一個(gè)對(duì)象池究竟持有哪些對(duì)象寺庄,在一開始的時(shí)候,就是知道的力崇。

其他接口和抽象類

除了上述三個(gè)核心接口之外斗塘,pool包還提供了另外三個(gè)接口:KeyedObjectPool、KeyedPoolableObjectFactory和KeyedObjectPoolFactory亮靴。這三個(gè)接口在用法上和上送接口完全一致馍盟,不一樣地方就在于,它們提供了“key”的功能茧吊,可以根據(jù)key獲取指定的對(duì)象贞岭。
此外八毯,pool包還有4個(gè)抽象類,BaseKeyedObjectPool瞄桨、BaseKeyedPoolableObjectFactory话速、BaseObjectPool和BasePoolableObjectFactory。光看名字也能看出來(lái)芯侥,這四個(gè)抽象類僅是對(duì)那四個(gè)接口的簡(jiǎn)單實(shí)現(xiàn)泊交,讓那些不方便實(shí)現(xiàn)接口的類,可以改為繼承柱查。

org.apache.commons.pool.impl包

了解了org.apache.commons.pool包的組成之后廓俭,再看org.apache.commons.pool.impl包就會(huì)清晰很多,在1.5.4的版本中org.apache.commons.pool.impl包由以下幾個(gè)類組成:

  • 標(biāo)準(zhǔn)實(shí)現(xiàn)
    • GenericKeyedObjectPool
    • GenericKeyedObjectPoolFactory
    • GenericObjectPool
    • GenericObjectPoolFactory
  • 基于堆棧的實(shí)現(xiàn)
    • StackKeyedObjectPool
    • StackKeyedObjectPoolFactory
    • StackObjectPool
    • StackObjectPoolFactory
  • 使用軟引用的對(duì)象池
    • SoftReferenceObjectPool
  • 其他(工具類)
    • CursorableLinkedList
    • CursorableSubList
    • EvictionTimer

在org.apache.commons.pool.impl包并不包含PoolableObjectFactory接口的實(shí)現(xiàn)類唉工,也就是說(shuō)研乒,PoolableObjectFactory接口是需要用戶自己去實(shí)現(xiàn)的。

GenericObjectPoolFactory

GenericObjectPoolFactory是ObjectPoolFactory接口的標(biāo)準(zhǔn)實(shí)現(xiàn)淋硝。初始化GenericObjectPoolFactory對(duì)象時(shí)必須傳入一個(gè)PoolableObjectFactory對(duì)象雹熬。同時(shí)用戶可以自己定義一些參數(shù),這些參數(shù)就是構(gòu)造一個(gè)pool對(duì)象是用到的屬性奖地。關(guān)于這些屬性橄唬,我們放到后面詳細(xì)介紹。一個(gè)GenericObjectPoolFactory對(duì)象初始化完成之后参歹,就可以調(diào)用它的createPool()方法仰楚,得到一個(gè)GenericObjectPool對(duì)象了。

GenericObjectPool

GenericObjectPool出于嚴(yán)謹(jǐn)?shù)目紤]犬庇,既繼承了BaseObjectPool又實(shí)現(xiàn)了ObjectPool僧界。在org.apache.commons.pool.impl包的packageinfo中可以看到這樣一段描述:“GenericObjectPool (GenericKeyedObjectPool) provides a more robust (but also more complicated) implementation of ObjectPool (KeyedObjectPool). ”,意思就是GenericObjectPool的實(shí)現(xiàn)更為健壯也更為復(fù)雜臭挽!它是整個(gè)commons-pool包的核心和基礎(chǔ)捂襟!接下來(lái),我將從參數(shù)屬性欢峰、內(nèi)部類和核心方法實(shí)現(xiàn)這幾個(gè)方面葬荷,詳細(xì)的解析GenericObjectPool類。

內(nèi)部屬性

GenericObjectPool的內(nèi)部(private)屬性纽帖、屬性的類型和屬性的作用宠漩,如下表所示:

名稱 類型 默認(rèn)值 作用
_maxIdle int 8 池中最多可容納的實(shí)例(instances)個(gè)數(shù)
_minIdle int 0 池中最少需要容納的實(shí)例(instances)個(gè)數(shù)
_maxActive int 8 池中最多可用的實(shí)例個(gè)數(shù)
_maxWait long -1 調(diào)用borrowObject方法時(shí),需要等待的最長(zhǎng)時(shí)間
_whenExhaustedAction byte 1 一組標(biāo)識(shí)位懊直,用來(lái)標(biāo)識(shí)當(dāng)發(fā)現(xiàn)池中的可用實(shí)例已經(jīng)用光時(shí)扒吁,需要做的動(dòng)作
_testOnBorrow boolean false 調(diào)用borrowObject方法時(shí),依據(jù)此標(biāo)識(shí)判斷是否需要對(duì)返回的結(jié)果進(jìn)行校驗(yàn)室囊,如果校驗(yàn)失敗會(huì)刪除當(dāng)前實(shí)例雕崩,并嘗試再次獲取
_testOnReturn boolean false 調(diào)用returnObject方法時(shí)魁索,依據(jù)此標(biāo)識(shí)判斷是否需要對(duì)返回的結(jié)果進(jìn)行校驗(yàn)
_testWhileIdle boolean false 閑置實(shí)例校驗(yàn)標(biāo)識(shí),如果校驗(yàn)失敗會(huì)刪除當(dāng)前實(shí)例
_timeBetweenEvictionRunsMillis long -1l 閑置實(shí)例校驗(yàn)器啟動(dòng)的時(shí)間間隔盼铁,單位是毫秒
_numTestsPerEvictionRun int 3 閑置實(shí)例校驗(yàn)器每次校驗(yàn)實(shí)例的個(gè)數(shù)
_minEvictableIdleTimeMillis long 1800000
_softMinEvictableIdleTimeMillis long -1
_lifo boolean true 池中實(shí)例的操作是否按照LIFO(后進(jìn)先出)的原則
_pool CursorableLinkedList null 用來(lái)存放實(shí)例對(duì)象
_evictionCursor Cursor null 迭代器的一類實(shí)現(xiàn)粗蔚,用來(lái)記錄那些需要被銷毀的對(duì)象實(shí)例
_factory PoolableObjectFactory null 完成對(duì)象操作的工廠類,需要用戶自己實(shí)現(xiàn)
_numActive int 0 用來(lái)記錄那些被使用捉貌,尚未歸還的實(shí)例數(shù)量
_evictor Evictor null 閑置實(shí)例校驗(yàn)器
_numInternalProcessing int 0 用來(lái)記錄那些處理中的實(shí)例
_allocationQueue LinkedList new LinkedList() 用來(lái)跟蹤所有調(diào)用borrowObject方法的線程

除了_testOnBorrow和_testOnReturn這兩個(gè)屬性支鸡,其余屬性的get/set方法全部是同步的(synchronized)。

內(nèi)部類

GenericObjectPool內(nèi)部一共定義了3個(gè)內(nèi)部類:

  • org.apache.commons.pool.impl.GenericObjectPool.Evictor:閑置實(shí)例校驗(yàn)(清除)器
    這個(gè)內(nèi)部的類的源碼如下:

    /**
     * The idle object evictor {@link TimerTask}.
     * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis
     */
    private class Evictor extends TimerTask {
        /**
         * Run pool maintenance.  Evict objects qualifying for eviction and then
         * invoke {@link GenericObjectPool#ensureMinIdle()}.
         */
        public void run() {
            try {
                evict();
            } catch(Exception e) {
                // ignored
            } catch(OutOfMemoryError oome) {
                // Log problem but give evictor thread a chance to continue in
                // case error is recoverable
                oome.printStackTrace(System.err);
            }
            try {
                ensureMinIdle();
            } catch(Exception e) {
                // ignored
            }
        }
    }

可以看到它是TimerTask的子類趁窃,這樣我們結(jié)合java.util.Timer類就可以做到定時(shí)的啟動(dòng)閑置實(shí)例校驗(yàn)。當(dāng)前啟動(dòng)閑置實(shí)例校驗(yàn)時(shí)急前,一共只執(zhí)行了兩個(gè)方法醒陆,先說(shuō)evict(),這個(gè)方法的主要作用是結(jié)合類的屬性完成閑置實(shí)例的校驗(yàn)和清理裆针,校驗(yàn)的邏輯也很簡(jiǎn)單刨摩,程序會(huì)首先檢查這個(gè)實(shí)例的空閑時(shí)間,空閑時(shí)間超過_minEvictableIdleTimeMillis屬性的值時(shí)就認(rèn)定需要清理世吨,當(dāng)_testWhileIdle屬性為ture時(shí)澡刹,程序還會(huì)將實(shí)例交給PoolableObjectFactory(用戶自定義的)再去校驗(yàn)一次,最后如果認(rèn)定需要清理耘婚,則調(diào)用PoolableObjectFactory的destroyObject方法罢浇,銷毀對(duì)象。

因?yàn)閑vict()在執(zhí)行的過程中有可能銷毀池中的對(duì)象沐祷,因此在方法結(jié)束后嚷闭,可能會(huì)出現(xiàn)的一種場(chǎng)景就是池中的對(duì)象少于minIdle的值,這個(gè)時(shí)候就需要執(zhí)行ensureMinIdle()方法赖临,重新完成“蓄池”的動(dòng)作胞锰。

  • org.apache.commons.pool.impl.GenericObjectPool.Config:一個(gè)內(nèi)部靜態(tài)常量類。
  • org.apache.commons.pool.impl.GenericObjectPool.Latch:Latch直譯過來(lái)是“門閂”的意思兢榨,它其實(shí)是對(duì)用戶“獲取對(duì)象”操作的一個(gè)封裝嗅榕,那究竟封裝了哪些信息呢?來(lái)看下這個(gè)類的兩個(gè)屬性吵聪。

        /** object timestamp pair allocated to this latch */
        private ObjectTimestampPair _pair;
        
        /** Wheter or not this latch may create an object instance */
        private boolean _mayCreate = false;

_pair屬性是ObjectTimestampPair的對(duì)象凌那,ObjectTimestampPair是在KeyedObjectPool的實(shí)現(xiàn)類GenericKeyedObjectPool中定義的一個(gè)內(nèi)部類,這個(gè)應(yīng)該是直接復(fù)用過來(lái)的暖璧,這個(gè)類也有兩個(gè)屬性案怯,一個(gè)是真實(shí)存放數(shù)據(jù)value,另一個(gè)是記錄對(duì)象創(chuàng)建時(shí)的時(shí)間戳的tstamp澎办。GenericObjectPool對(duì)象內(nèi)部維護(hù)的_pool屬性中嘲碱,存放的就是ObjectTimestampPair對(duì)象金砍。

        /** Object instance */
        Object value;
        
        /** timestamp */
        long tstamp;
        
        /**
         * Create a new ObjectTimestampPair using the given object and the current system time.
         * @param val object instance
         */
        ObjectTimestampPair(Object val) {
            this(val, System.currentTimeMillis());
        }
        
        ......

_mayCreate的作用可以理解為一個(gè)標(biāo)識(shí),用來(lái)標(biāo)識(shí)用戶的這次“獲取對(duì)象”的操作是否需要?jiǎng)?chuàng)建一個(gè)新的實(shí)例麦锯。

核心方法實(shí)現(xiàn)

  • addObject()
    在方法的注釋上恕稠,作者寫的很清楚,addObject的作用就是創(chuàng)建一個(gè)對(duì)象,并將對(duì)象“蓄”到池中扶欣。一般使用池的時(shí)候鹅巍,都會(huì)初始化一些對(duì)象在池中,即作者所說(shuō)的“pre-loading”料祠。方法比較簡(jiǎn)單骆捧,真正干活的,是內(nèi)部方法addObjectToPool(Object, boolean)髓绽。
    /**
     * Create an object, and place it into the pool.
     * addObject() is useful for "pre-loading" a pool with idle objects.
     */
    public void addObject() throws Exception {
        ....
            addObjectToPool(obj, false);
        ....
    }

按照作者的描述addObjectToPool方法做了三件事情:首先校驗(yàn)當(dāng)前拿到的這個(gè)對(duì)象是否合法敛苇,然后判斷是需要將它銷毀掉還是放到內(nèi)部的_pool對(duì)象中。

    /**
     * <p>Adds an object to the pool.</p>
     * 
     * <p>Validates the object if testOnReturn == true and passivates it before returning it to the pool.
     * if validation or passivation fails, or maxIdle is set and there is no room in the pool, the instance
     * is destroyed.</p>
     * 
     * <p>Calls {@link #allocate()} on successful completion</p>
     * 
     * @param obj instance to add to the pool
     * @param decrementNumActive whether or not to decrement the active count
     * @throws Exception
     */
    private void addObjectToPool(Object obj, boolean decrementNumActive) throws Exception {
        // 判斷object是否合法
        boolean shouldDestroy = !success;
        ....
        // 將對(duì)象蓄到池中
         _pool.addFirst(new ObjectTimestampPair(obj));
        // 
        allocate();
        // Destroy the instance if necessary
        if(shouldDestroy) {
            _factory.destroyObject(obj);
        }
    }

在完成“蓄池”后顺呕,需要給正在獲取對(duì)象的現(xiàn)在重新分配資源枫攀,及調(diào)用allocate方法。

    /**
     * Allocate available instances to latches in the allocation queue.  Then
     * set _mayCreate to true for as many additional latches remaining in queue
     * as _maxActive allows.
     */
    private synchronized void allocate() {
        if (isClosed()) return;

        // First use any objects in the pool to clear the queue
        // 首先從池里獲取對(duì)象實(shí)例
        for (;;) {
            if (!_pool.isEmpty() && !_allocationQueue.isEmpty()) {
                Latch latch = (Latch) _allocationQueue.removeFirst();
                latch.setPair((ObjectTimestampPair) _pool.removeFirst());
                _numInternalProcessing++; // 表示正在處理中的對(duì)象個(gè)數(shù)
                synchronized (latch) {
                    latch.notify();//通知被阻塞等待的latch
                }
            } else {
                break;
            }
        }

        // Second utilise any spare capacity to create new objects
        // 如果池已經(jīng)空了株茶,又沒有到達(dá)容量上限来涨,則標(biāo)識(shí)需要重新生成
        for(;;) {
            if((!_allocationQueue.isEmpty()) && (_maxActive < 0 || (_numActive + _numInternalProcessing) < _maxActive)) {
                Latch latch = (Latch) _allocationQueue.removeFirst();
                latch.setMayCreate(true);
                _numInternalProcessing++;
                synchronized (latch) {
                    latch.notify();
                }
            } else {
                break;
            }
        }
    }
  • borrowObject()
    方法的功能很簡(jiǎn)單,就是從池中獲取一個(gè)對(duì)象启盛,但實(shí)施起來(lái)卻比較復(fù)雜蹦掐,尤其在多線程的場(chǎng)景中。來(lái)看一下作者在設(shè)計(jì)這個(gè)方法時(shí)都考慮了哪些東西驰徊。

首先笤闯,如果池中有可用的對(duì)象,那么根據(jù)配置的獲取原則(后入先出棍厂,或者先入先出)颗味,將對(duì)象激活并返回,如果設(shè)置了testOnBorrow牺弹,那么在返回之前還將進(jìn)行校驗(yàn)浦马,如果校驗(yàn)不通過則銷毀當(dāng)前對(duì)象,并繼續(xù)這個(gè)過程张漂,直至從池中找到復(fù)合要求的對(duì)象或者池中已經(jīng)沒有可用的對(duì)象為止晶默。

If there is an idle instance available in the pool, then either the most-recently returned (if lifo == true) or "oldest" (lifo == false) instance sitting idle in the pool will be activated and returned. If activation fails, or testOnBorrow is set to true and validation fails, the instance is destroyed and the next available instance is examined. This continues until either a valid instance is returned or there are no more idle instances available.

如果池中沒有可用的對(duì)象,接下來(lái)的動(dòng)作要結(jié)合maxActive航攒、whenExhaustedAction和maxWait這三個(gè)屬性的值綜合判斷磺陡。如果當(dāng)前池中已經(jīng)被取用的對(duì)象小于maxActive的值,則會(huì)創(chuàng)建一個(gè)新的對(duì)象,并將它返回币他。如果池中的資源已經(jīng)被耗盡(當(dāng)前沒有可用的對(duì)象并且已取用的對(duì)象達(dá)到maxActive的值)坞靶,方法會(huì)首先阻塞,如果阻塞的時(shí)間已經(jīng)超過了設(shè)置(maxWait的值)蝴悉,那么接下來(lái)有兩種選擇彰阴,一種選擇是拋異常,另一種則是無(wú)視maxActive的配置拍冠,繼續(xù)擴(kuò)充池的容量尿这。

If there are no idle instances available in the pool, behavior depends on the maxActive and (if applicable) whenExhaustedAction and maxWait properties. If the number of instances checked out from the pool is less than maxActive, a new instance is created, activated and (if applicable) validated and returned to the caller.If the pool is exhausted (no available idle instances and no capacity to create new ones), this method will either block (WHEN_EXHAUSTED_BLOCK), throw a NoSuchElementException (WHEN_EXHAUSTED_FAIL), or grow (WHEN_EXHAUSTED_GROW - ignoring maxActive). The length of time that this method will block when whenExhaustedAction == WHEN_EXHAUSTED_BLOCK is determined by the maxWait property.

當(dāng)池中的資源被耗盡時(shí),所以的線程都會(huì)阻塞庆杜,都在等待從池中獲取可用的資源射众,1.5之后的commons-pool設(shè)計(jì)了一種“公平”算法,確保線程們是按照請(qǐng)求的順序晃财,依次獲取對(duì)象實(shí)例责球。

When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive available instances in request arrival order.

上文的描述中,已經(jīng)基本把整個(gè)方法的邏輯交代清楚了拓劝,接下來(lái)我們就來(lái)看一下代碼是如何實(shí)現(xiàn)的。

    public Object borrowObject() throws Exception {
        // 得到當(dāng)前時(shí)間
        long starttime = System.currentTimeMillis();
        // 新建一個(gè)閂鎖嘉裤,用來(lái)實(shí)現(xiàn)“公平”算法
        Latch latch = new Latch();
        byte whenExhaustedAction;
        long maxWait;
        /*
         * 同步的將閂鎖放入隊(duì)列郑临,為了避免死鎖,沒有調(diào)用屬性的get的方法屑宠,而是指定賦值厢洞。
         * 在高并發(fā)的環(huán)境下,同時(shí)有多個(gè)線程請(qǐng)求borrowObject方法典奉,此時(shí)躺翻,每個(gè)線程都會(huì)新生成一個(gè)Latch對(duì)象以及whenExhaustedAction和maxWait,
         * 程序會(huì)同步的將Latch對(duì)象放入_allocationQueue鏈表中卫玖,然后執(zhí)行allocate方法(allocate的作用見上文)公你。
         */
        synchronized (this) {
            // Get local copy of current config. Can't sync when used later as
            // it can result in a deadlock. Has the added advantage that config
            // is consistent for entire method execution
            whenExhaustedAction = _whenExhaustedAction;
            maxWait = _maxWait;

            // Add this request to the queue
            _allocationQueue.add(latch);

            // Work the allocation queue, allocating idle instances and
            // instance creation permits in request arrival order
            allocate();
        }
        // 開始迭代,直到返回對(duì)象或拋出異常假瞬!for(;;)是死循環(huán)的一種寫法
        for(;;) {
            synchronized (this) {
                assertOpen();
            }

            // If no object was allocated from the pool above 無(wú)法從池中獲取對(duì)象
            if(latch.getPair() == null) {
                // check if we were allowed to create one 如果池中的對(duì)象還沒有達(dá)到maxActive陕靠,標(biāo)識(shí)可以創(chuàng)建一個(gè)新的對(duì)象
                if(latch.mayCreate()) {
                    // allow new object to be created
                } else {
                    // the pool is exhausted 池中的資源被用光后,依照屬性的whenExhaustedAction的值脱茉,完成相應(yīng)的動(dòng)作剪芥,
                    switch(whenExhaustedAction) {
                        // 繼續(xù)擴(kuò)充池的容量
                        case WHEN_EXHAUSTED_GROW:
                            // allow new object to be created
                            synchronized (this) {
                                // Make sure another thread didn't allocate us an object
                                // or permit a new object to be created
                                if (latch.getPair() == null && !latch.mayCreate()) {
                                    _allocationQueue.remove(latch); // 這行代碼的意思是不在繼續(xù)為latch分配對(duì)象
                                    _numInternalProcessing++;
                                }
                            }
                            break;
                        // 返回失敗
                        case WHEN_EXHAUSTED_FAIL:
                            synchronized (this) {
                                // Make sure allocate hasn't already assigned an object
                                // in a different thread or permitted a new object to be created
                                if (latch.getPair() != null || latch.mayCreate()) {
                                    break;
                                }
                                _allocationQueue.remove(latch);
                            }
                            throw new NoSuchElementException("Pool exhausted"); // 直接拋異常
                        // 阻塞等待
                        case WHEN_EXHAUSTED_BLOCK:
                            try {
                                synchronized (latch) {
                                    // Before we wait, make sure another thread didn't allocate us an object
                                    // or permit a new object to be created
                                    if (latch.getPair() == null && !latch.mayCreate()) {
                                        if(maxWait <= 0) {
                                            latch.wait();
                                        } else {
                                            // this code may be executed again after a notify then continue cycle
                                            // so, need to calculate the amount of time to wait
                                            // 計(jì)算阻塞時(shí)間
                                            final long elapsed = (System.currentTimeMillis() - starttime);
                                            final long waitTime = maxWait - elapsed;
                                            if (waitTime > 0)
                                            {
                                                latch.wait(waitTime);
                                            }
                                        }
                                    } else {
                                        break;
                                    }
                                }
                            } catch(InterruptedException e) {
                                Thread.currentThread().interrupt();
                                throw e;
                            }
                            // 等待超時(shí),拋異常
                            if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
                                synchronized(this) {
                                    // Make sure allocate hasn't already assigned an object
                                    // in a different thread or permitted a new object to be created
                                    if (latch.getPair() == null && !latch.mayCreate()) {
                                        // Remove latch from the allocation queue
                                        _allocationQueue.remove(latch);
                                    } else {
                                        break;
                                    }
                                }
                                throw new NoSuchElementException("Timeout waiting for idle object");
                            } else {
                                continue; // keep looping
                            }
                        default:
                            throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction +
                                    " not recognized.");
                    }
                }
            }
            // 開始新生成一個(gè)對(duì)象
            boolean newlyCreated = false;
            if(null == latch.getPair()) {
                try {
                    Object obj = _factory.makeObject();
                    latch.setPair(new ObjectTimestampPair(obj));
                    newlyCreated = true;
                } finally {
                    if (!newlyCreated) {
                        // object cannot be created
                        synchronized (this) {
                            _numInternalProcessing--;
                            // No need to reset latch - about to throw exception
                            allocate();
                        }
                    }
                }
            }
            // activate & validate the object 激活并返回對(duì)象
            try {
                _factory.activateObject(latch.getPair().value);
                if(_testOnBorrow &&
                        !_factory.validateObject(latch.getPair().value)) {
                    throw new Exception("ValidateObject failed");
                }
                synchronized(this) {
                    _numInternalProcessing--;
                    _numActive++;
                }
                return latch.getPair().value;
            }
            // 如果在激活對(duì)象的過程中出現(xiàn)異常
            catch (Throwable e) {
                // object cannot be activated or is invalid
                try {
                    _factory.destroyObject(latch.getPair().value); // 銷毀這個(gè)對(duì)象
                } catch (Throwable e2) {
                    // cannot destroy broken object
                }
                synchronized (this) {
                    _numInternalProcessing--; // 修改正在處理中的對(duì)象個(gè)數(shù)
                    if (!newlyCreated) {
                        latch.reset();
                        _allocationQueue.add(0, latch);
                    }
                    allocate(); // 重新分配
                }
                if(newlyCreated) {
                    // 如果是新創(chuàng)建的對(duì)象又無(wú)法激活琴许,會(huì)拋異常
                    throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
                }
                else {
                    continue; // keep looping 
                }
            }
        }
    }

通過對(duì)上述的源碼分析可以看到税肪,程序?qū)﹃P(guān)鍵資源的操作都是同步的(synchronized),按照資源類型大致可以分為:

  1. 全局屬性配置:_whenExhaustedAction、_maxWait益兄。屬于全局配置锻梳,當(dāng)pool初始化時(shí)就已經(jīng)確定。
  2. 全局資源變量:_allocationQueue偏塞、_pool和_numInternalProcessing唱蒸。用作全局控制,操作的結(jié)果會(huì)影響其他方法灸叼。
  3. 方法內(nèi)部變量:latch神汹。每個(gè)調(diào)用borrowObject()方法的線程都會(huì)生成一個(gè)latch對(duì)象。

同步的處理操作解決了并發(fā)問題古今,但同時(shí)會(huì)有性能上的損失屁魏,對(duì)于一個(gè)工具類的項(xiàng)目,我覺得性能只是考慮解決方案的一部分捉腥,功能的穩(wěn)定性才是需要關(guān)注的重點(diǎn)氓拼!

  • returnObject(Object) 有了解析borrowObject()方法的經(jīng)驗(yàn),再看returnObject(Object)方法抵碟,就比較簡(jiǎn)單了桃漾。
    /**
     * <p>Returns an object instance to the pool.</p>
     * 
     * <p>If {@link #getMaxIdle() maxIdle} is set to a positive value and the number of idle instances
     * has reached this value, the returning instance is destroyed.</p>
     * 
     * <p>If {@link #getTestOnReturn() testOnReturn} == true, the returning instance is validated before being returned
     * to the idle instance pool.  In this case, if validation fails, the instance is destroyed.</p>
     * 
     * <p><strong>Note: </strong> There is no guard to prevent an object
     * being returned to the pool multiple times. Clients are expected to
     * discard references to returned objects and ensure that an object is not
     * returned to the pool multiple times in sequence (i.e., without being
     * borrowed again between returns). Violating this contract will result in
     * the same object appearing multiple times in the pool and pool counters
     * (numActive, numIdle) returning incorrect values.</p>
     *
     * 注意:一定要避免一個(gè)對(duì)象被多次“返還”的情況發(fā)生!
     * 
     * @param obj instance to return to the pool
     */
    public void returnObject(Object obj) throws Exception {
        try {
            addObjectToPool(obj, true);
        } catch (Exception e) {
            if (_factory != null) {
                try {
                    _factory.destroyObject(obj);
                } catch (Exception e2) {
                    // swallowed
                }
                // TODO: Correctness here depends on control in addObjectToPool.
                // These two methods should be refactored, removing the
                // "behavior flag", decrementNumActive, from addObjectToPool.
                synchronized(this) {
                    _numActive--;
                    allocate();
                }
            }
        }
    }

示例:數(shù)據(jù)庫(kù)連接池

講了這么多拟逮,是時(shí)候自己動(dòng)手練練了撬统。這次的例子很簡(jiǎn)單,就是使用commons-pool構(gòu)造自己的數(shù)據(jù)庫(kù)連接池敦迄,既是對(duì)commons-pool使用方法的總結(jié)恋追,也順便熟悉熟悉數(shù)據(jù)庫(kù)連接池的業(yè)務(wù),為馬上要開始的commons-dbcp包的源碼解析熱身罚屋。

對(duì)象構(gòu)造工廠

package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.commons.pool.PoolableObjectFactory;

/**
 * 依賴Apache Commons Pool實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接池苦囱,定義一個(gè)數(shù)據(jù)連接對(duì)象的工廠
 * 
 * @author 許廣 @
 * 
 */
public class ConnectionPoolFactory implements PoolableObjectFactory {

    private DataSource dataSource;

    public ConnectionPoolFactory(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Object makeObject() throws Exception {
        return dataSource.getConnection();
    }

    @Override
    public void destroyObject(Object obj) throws Exception {
        ((Connection) obj).close();
    }

    @Override
    public boolean validateObject(Object obj) {
        try {
            Statement statement = ((Connection) obj).createStatement();
            ResultSet rs = statement.executeQuery(" SELECT 1 FROM DUAL");
            while (rs.next()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void activateObject(Object obj) throws Exception {
        try {
            Statement statement = ((Connection) obj).createStatement();
            statement.execute(" SELECT 1 FROM DUAL");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void passivateObject(Object obj) throws Exception {

    }

}

測(cè)試連接池的使用

package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.commons.pool.impl.GenericObjectPool;

import oracle.jdbc.pool.OracleConnectionPoolDataSource;

/**
 * 
 * 數(shù)據(jù)庫(kù)連接池測(cè)試
 * 
 * @author 許廣 @
 * 
 */
public class ConnectionPoolTest {
    public static void main(String arg[]) throws Exception {
        
        System.out.println("初始化數(shù)據(jù)源");
        OracleConnectionPoolDataSource dataSource = new OracleConnectionPoolDataSource();
        dataSource.setURL("jdbc:oracle:thin:@192.168.22.63:1521:orcl");
        dataSource.setUser("scott");
        dataSource.setPassword("tiger");
        
        System.out.println("創(chuàng)建數(shù)據(jù)庫(kù)連接池");
        ConnectionPoolFactory factory = new ConnectionPoolFactory(dataSource);
        GenericObjectPool pool = new GenericObjectPool(factory);
        System.out.println("當(dāng)前數(shù)據(jù)庫(kù)連接池的容量" + pool.getNumActive());
        System.out.println("獲取一個(gè)數(shù)據(jù)庫(kù)連接");
        Connection conn = (Connection)pool.borrowObject();
        System.out.println("當(dāng)前數(shù)據(jù)庫(kù)連接池的容量" + pool.getNumActive());
        System.out.println("開始執(zhí)行sql腳本");
        Statement statement = conn.createStatement();
        ResultSet rs = statement.executeQuery("SELECT ID FROM EASYPASSPORT_USERS ");
        while (rs.next()) {
            long id = rs.getLong(1);
            System.out.println("從數(shù)據(jù)庫(kù)中得到一條記錄的值" + id);
        }
        rs.close();
        statement.close();
        System.out.println("將對(duì)象返還給連接池");
        pool.returnObject(conn);
    }
}

得到結(jié)果

初始化數(shù)據(jù)源
創(chuàng)建數(shù)據(jù)庫(kù)連接池
當(dāng)前數(shù)據(jù)庫(kù)連接池的容量0
獲取一個(gè)數(shù)據(jù)庫(kù)連接
當(dāng)前數(shù)據(jù)庫(kù)連接池的容量1
開始執(zhí)行sql腳本
從數(shù)據(jù)庫(kù)中得到一條記錄的值999
將對(duì)象返還給連接池

總結(jié)

理論上來(lái)講,如果在系統(tǒng)資源有充足的前提下脾猛,使用任何創(chuàng)建起來(lái)比較占用資源的對(duì)象撕彤,都應(yīng)該“池化”。最典型尖滚,應(yīng)用最多的就數(shù)據(jù)庫(kù)連接池(包括關(guān)系型和非關(guān)系型數(shù)據(jù)庫(kù))喉刘。一個(gè)池應(yīng)至少應(yīng)該包含以下兩個(gè)功能,一是對(duì)象的緩存漆弄、獲取和歸還睦裳,二是池自身屬性的自動(dòng)維護(hù)更新。這兩個(gè)都屬于池的核心功能撼唾,實(shí)現(xiàn)的質(zhì)量高低廉邑,直接決定池的品質(zhì)。不同通途的池可在這兩個(gè)功能的基礎(chǔ)上再擴(kuò)展出一些差異話的屬性。
commons-pool給出了一個(gè)池的經(jīng)典實(shí)現(xiàn)蛛蒙,而且源碼簡(jiǎn)潔清晰糙箍,讀起來(lái)有一種設(shè)計(jì)的美感。平時(shí)在日常工作中牵祟,如果需要對(duì)象池深夯,commons-pool是你不二的選擇。

參考

關(guān)于DBCP及使用诺苹,純JDBC架構(gòu)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末咕晋,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子收奔,更是在濱河造成了極大的恐慌掌呜,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,682評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件坪哄,死亡現(xiàn)場(chǎng)離奇詭異质蕉,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)翩肌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門模暗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人念祭,你說(shuō)我怎么就攤上這事汰蓉。” “怎么了棒卷?”我有些...
    開封第一講書人閱讀 165,083評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)祝钢。 經(jīng)常有香客問我比规,道長(zhǎng),這世上最難降的妖魔是什么拦英? 我笑而不...
    開封第一講書人閱讀 58,763評(píng)論 1 295
  • 正文 為了忘掉前任蜒什,我火速辦了婚禮,結(jié)果婚禮上疤估,老公的妹妹穿的比我還像新娘灾常。我一直安慰自己,他們只是感情好铃拇,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評(píng)論 6 392
  • 文/花漫 我一把揭開白布钞瀑。 她就那樣靜靜地躺著,像睡著了一般慷荔。 火紅的嫁衣襯著肌膚如雪雕什。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,624評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音贷岸,去河邊找鬼壹士。 笑死,一個(gè)胖子當(dāng)著我的面吹牛偿警,可吹牛的內(nèi)容都是我干的躏救。 我是一名探鬼主播,決...
    沈念sama閱讀 40,358評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼螟蒸,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼盒使!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起尿庐,我...
    開封第一講書人閱讀 39,261評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤忠怖,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后抄瑟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凡泣,經(jīng)...
    沈念sama閱讀 45,722評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年皮假,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了鞋拟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,030評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡惹资,死狀恐怖贺纲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情褪测,我是刑警寧澤猴誊,帶...
    沈念sama閱讀 35,737評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站侮措,受9級(jí)特大地震影響懈叹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜分扎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評(píng)論 3 330
  • 文/蒙蒙 一澄成、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧畏吓,春花似錦墨状、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至宏悦,卻和暖如春通今,著一層夾襖步出監(jiān)牢的瞬間粥谬,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工辫塌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留漏策,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,237評(píng)論 3 371
  • 正文 我出身青樓臼氨,卻偏偏與公主長(zhǎng)得像掺喻,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子储矩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評(píng)論 2 355

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理感耙,服務(wù)發(fā)現(xiàn),斷路器持隧,智...
    卡卡羅2017閱讀 134,659評(píng)論 18 139
  • 個(gè)人筆記即硼,方便自己查閱使用 Contents Java LangAssignment, ReferenceData...
    freenik閱讀 1,384評(píng)論 0 6
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,509評(píng)論 0 23
  • 日子過得飛快,10月已經(jīng)過了三周屡拨,又到了每周總結(jié)的時(shí)間了只酥,但是我還從來(lái)沒有寫到過1000字,每次都覺得詞窮呀狼。 這周...
    八月芳菲閱讀 214評(píng)論 0 0
  • 彭小六、剽悍一只貓何許人也貌踏? 一個(gè)是簡(jiǎn)書頭牌作者十饥、月入10萬(wàn)+的斜杠青年代表;一個(gè)是獨(dú)立采訪人祖乳、坐擁幾十萬(wàn)粉絲的自...
    危笑天閱讀 761評(píng)論 4 9