Pool, SimplePool, Synchronized Pool parsing in Android V4 package

Keywords: Android Java Mobile

Due to the limitation of Android mobile phone hardware resources, Android uses Pool in many places, especially for Velocity Tracker classes that need to be invoked native ly, such as Touch, Fling and other gesture speeds, the document indicates that the invocation method must be:

// Establish
VelocityTracker mVelocityTracker = VelocityTracker.obtain();

// recovery
mVelocityTracker.recycle();
mVelocityTracker = null;

Synchronized Pool is used internally to implement:

public final class VelocityTracker {
    private static final SynchronizedPool<VelocityTracker> sPool =
            new SynchronizedPool<VelocityTracker>(2);
    // Eliminate other code
}

Its implementation includes three classes and interfaces: Pool interface, SimplePool class and Synchronized Pool class. In fact, the modern code is in android.util.Pools class. The code structure is as follows:
Pool interface

public static interface Pool<T> {
    public T acquire();
    public boolean release(T instance);
}
Two methods are defined, one is obtained from Pool and the other is released into Pool, which is very simple.

SimplePool class

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];
    }

    // ...
}

Use an Object array to store, so the capacity of the Pool is fixed, so the Object array here is the simplest, if you need to implement an automatically expandable Pool, you can replace the Object array with a linked list.

SynchronizedPool class

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);
        }
    }
}

There is only one lock (mLock) added here, and any object in Java can be used as a lock. For example, if the outside code uses synchronized (mSynchronized Pool), there will be problems, or even deadlocks. For reference: synchronized(this) in Java How to use

How to use these classes is as follows:

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);
   }
   // ...
}
ok~is very concise, so it seems easy to implement a Pool.

Posted by awais_ciit on Sun, 06 Jan 2019 00:18:09 -0800