Skip to content

Instantly share code, notes, and snippets.

@czyrux
Created July 23, 2016 11:27
Show Gist options
  • Save czyrux/dff4a86fa76aad9cdcdf2c9a8c1cb8d6 to your computer and use it in GitHub Desktop.
Save czyrux/dff4a86fa76aad9cdcdf2c9a8c1cb8d6 to your computer and use it in GitHub Desktop.
Leaner version of a Simple (non-synchronized) pool of objects. This Pool does not do any check whether an object to be released is already or not in the pool, unlike android.support.v4.util.Pools.SimplePool
import android.support.v4.util.Pools;
/**
* Simple (non-synchronized) pool of objects. This Pool does not do any check whether an object to be released is
* already in the pool, unlike {@link android.support.v4.util.Pools.SimplePool}
*
* @param <T> The pooled type.
*/
public class UncheckedPool<T> implements Pools.Pool<T> {
private final Object[] mPool;
private int mPoolSize;
/**
* Creates a new instance.
*
* @param maxPoolSize The max pool size.
*
* @throws IllegalArgumentException If the max pool size is less than zero.
*/
public UncheckedPool(final int maxPoolSize) {
if (maxPoolSize <= 0) {
throw new IllegalArgumentException("The max pool size must be > 0");
}
mPool = new Object[maxPoolSize];
}
@Override
@SuppressWarnings("unchecked")
public T acquire() {
if (mPoolSize > 0) {
final int lastPooledIndex = mPoolSize - 1;
T instance = (T) mPool[lastPooledIndex];
mPool[lastPooledIndex] = null;
mPoolSize--;
return instance;
}
return null;
}
@Override
public boolean release(final T instance) {
if (mPoolSize < mPool.length) {
mPool[mPoolSize] = instance;
mPoolSize++;
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment