| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.app.servertransaction; |
| 18 |
|
| 19 |
import java.util.ArrayList; |
| 20 |
import java.util.HashMap; |
| 21 |
import java.util.Map; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
class ObjectPool { |
| 28 |
|
| 29 |
private static final Object sPoolSync = new Object(); |
| 30 |
private static final Map<Class, ArrayList<? extends ObjectPoolItem>> sPoolMap = |
| 31 |
new HashMap<>(); |
| 32 |
|
| 33 |
private static final int MAX_POOL_SIZE = 50; |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
public static <T extends ObjectPoolItem> T obtain(Class<T> itemClass) { |
| 41 |
synchronized (sPoolSync) { |
| 42 |
@SuppressWarnings("unchecked") |
| 43 |
final ArrayList<T> itemPool = (ArrayList<T>) sPoolMap.get(itemClass); |
| 44 |
if (itemPool != null && !itemPool.isEmpty()) { |
| 45 |
return itemPool.remove(itemPool.size() - 1); |
| 46 |
} |
| 47 |
return null; |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
public static <T extends ObjectPoolItem> void recycle(T item) { |
| 57 |
synchronized (sPoolSync) { |
| 58 |
@SuppressWarnings("unchecked") |
| 59 |
ArrayList<T> itemPool = (ArrayList<T>) sPoolMap.get(item.getClass()); |
| 60 |
if (itemPool == null) { |
| 61 |
itemPool = new ArrayList<>(); |
| 62 |
sPoolMap.put(item.getClass(), itemPool); |
| 63 |
} |
| 64 |
|
| 65 |
final int size = itemPool.size(); |
| 66 |
for (int i = 0; i < size; i++) { |
| 67 |
if (itemPool.get(i) == item) { |
| 68 |
throw new IllegalStateException("Trying to recycle already recycled item"); |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
if (size < MAX_POOL_SIZE) { |
| 73 |
itemPool.add(item); |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
} |