Simple (non-synchronized) pool of objects. @param The pooled type.
| 80 | * @param <T> The pooled type. |
| 81 | */ |
| 82 | public static class SimplePool<T> implements Pool<T> { |
| 83 | private final Object[] mPool; |
| 84 | |
| 85 | private int mPoolSize; |
| 86 | |
| 87 | /** |
| 88 | * Creates a new instance. |
| 89 | * |
| 90 | * @param maxPoolSize The max pool size. |
| 91 | * |
| 92 | * @throws IllegalArgumentException If the max pool size is less than zero. |
| 93 | */ |
| 94 | public SimplePool(int maxPoolSize) { |
| 95 | if (maxPoolSize <= 0) { |
| 96 | throw new IllegalArgumentException("The max pool size must be > 0"); |
| 97 | } |
| 98 | mPool = new Object[maxPoolSize]; |
| 99 | } |
| 100 | |
| 101 | @Override |
| 102 | @SuppressWarnings("unchecked") |
| 103 | public T acquire() { |
| 104 | if (mPoolSize > 0) { |
| 105 | final int lastPooledIndex = mPoolSize - 1; |
| 106 | T instance = (T) mPool[lastPooledIndex]; |
| 107 | mPool[lastPooledIndex] = null; |
| 108 | mPoolSize--; |
| 109 | return instance; |
| 110 | } |
| 111 | return null; |
| 112 | } |
| 113 | |
| 114 | @Override |
| 115 | public boolean release(@NonNull T instance) { |
| 116 | if (isInPool(instance)) { |
| 117 | throw new IllegalStateException("Already in the pool!"); |
| 118 | } |
| 119 | if (mPoolSize < mPool.length) { |
| 120 | mPool[mPoolSize] = instance; |
| 121 | mPoolSize++; |
| 122 | return true; |
| 123 | } |
| 124 | return false; |
| 125 | } |
| 126 | |
| 127 | private boolean isInPool(@NonNull T instance) { |
| 128 | for (int i = 0; i < mPoolSize; i++) { |
| 129 | if (mPool[i] == instance) { |
| 130 | return true; |
| 131 | } |
| 132 | } |
| 133 | return false; |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Synchronized) pool of objects. |
nothing calls this directly
no outgoing calls
no test coverage detected