溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Pool, SimplePool與SynchronizedPool

發(fā)布時(shí)間:2020-08-11 09:50:27 來源:網(wǎng)絡(luò) 閱讀:9127 作者:zhlwish 欄目:移動(dòng)開發(fā)

因?yàn)橛布Y源的限制,Android在很多地方都使用了Pool的,特別是對(duì)于需要通過native的方式調(diào)用資源,比如專門用于獲取Touch、Flinging以及其他手勢(shì)速度的VelocityTracker類,文檔中指明了調(diào)用方式必須是:

// 創(chuàng)建
VelocityTracker mVelocityTracker = VelocityTracker.obtain();

// 回收
mVelocityTracker.recycle();
mVelocityTracker = null;

其內(nèi)部使用了SynchronizedPool來實(shí)現(xiàn):

public final class VelocityTracker {
    private static final SynchronizedPool<VelocityTracker> sPool =
            new SynchronizedPool<VelocityTracker>(2);
    // 省略其他代碼
}

其實(shí)現(xiàn)包括三個(gè)類和接口:Pool接口, SimplePool類與SynchronizedPool類,其實(shí)現(xiàn)代碼在android.util.Pools類中。代碼結(jié)構(gòu)如下:


Pool接口

public static interface Pool<T> {
    public T acquire();
    public boolean release(T instance);
}

    定義了兩個(gè)方法,一個(gè)從Pool中獲取,另一個(gè)將對(duì)象釋放到Pool中,非常簡(jiǎn)潔。


SimplePool類

public static class SimplePool<T> implements Pool<T> {
    private final Object[] mPool;
    private int mPoolSize;

    public SimplePool(int maxPoolSize) {
        if (maxPoolSize <= 0) {
            throw new IllegalArgumentException("The max pool size must be > 0");
        }
        mPool = new Object[maxPoolSize];
    }
 
    // ...
}

使用一個(gè)Object數(shù)組來存放,因此Pool的容量是固定的,因此這里用Object數(shù)組是最簡(jiǎn)單的,如果需要實(shí)現(xiàn)可以自動(dòng)擴(kuò)展的Pool,大可以將Object數(shù)組替換成鏈表。


SynchronizedPool類

public static class SynchronizedPool<T> extends SimplePool<T> {
    private final Object mLock = new Object();
    // ...
        
    public T acquire() {
        synchronized (mLock) {
            return super.acquire();
        }
    }
        
    public boolean release(T element) {
        synchronized (mLock) {
            return super.release(element);
        }
    }
}

這里只是增加了一個(gè)鎖(mLock),在Java里面任何一個(gè)對(duì)象都可以當(dāng)作鎖。至于為什么直接用synchronized(this),一般認(rèn)為synchronized(this)這樣是不好的,舉個(gè)例子,如果外面的代碼使用了synchronized(mSynchronizedPool)就會(huì)出現(xiàn)問題了,甚至有可能死鎖。可以參考:Avoid synchronized(this) in Java?


如何使用

如何使用這幾個(gè)類呢,方法如下:

public class MyPooledClass {  
    private static final SynchronizedPool sPool = new SynchronizedPool(10);
    
   public static MyPooledClass obtain() {
       MyPooledClass instance = sPool.acquire();
       return (instance != null) ? instance : new MyPooledClass();
   }

   public void recycle() {
        // Clear state if needed.
        sPool.release(this);
   }
   // ...
}

非常簡(jiǎn)潔,看來實(shí)現(xiàn)一個(gè)Pool也是一件很容易的事情。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI