1 /*
2  * Copyright 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
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  * An object pool that can provide reused objects if available.
25  * @hide
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      * Obtain an instance of a specific class from the pool
37      * @param itemClass The class of the object we're looking for.
38      * @return An instance or null if there is none.
39      */
obtain(Class<T> itemClass)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      * Recycle the object to the pool. The object should be properly cleared before this.
53      * @param item The object to recycle.
54      * @see ObjectPoolItem#recycle()
55      */
recycle(T item)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             // Check if the item is already in the pool
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 }
78