ObjectPool.java revision 5249bb11b7644be073263138dab5c12d7de4a078
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
17package android.app.servertransaction;
18
19import java.util.HashMap;
20import java.util.LinkedList;
21import java.util.Map;
22
23/**
24 * An object pool that can provide reused objects if available.
25 * @hide
26 */
27class ObjectPool {
28
29    private static final Object sPoolSync = new Object();
30    private static final Map<Class, LinkedList<? 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     */
40    public static <T extends ObjectPoolItem> T obtain(Class<T> itemClass) {
41        synchronized (sPoolSync) {
42            @SuppressWarnings("unchecked")
43            LinkedList<T> itemPool = (LinkedList<T>) sPoolMap.get(itemClass);
44            if (itemPool != null && !itemPool.isEmpty()) {
45                return itemPool.poll();
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     */
56    public static <T extends ObjectPoolItem> void recycle(T item) {
57        synchronized (sPoolSync) {
58            @SuppressWarnings("unchecked")
59            LinkedList<T> itemPool = (LinkedList<T>) sPoolMap.get(item.getClass());
60            if (itemPool == null) {
61                itemPool = new LinkedList<>();
62                sPoolMap.put(item.getClass(), itemPool);
63            }
64            if (itemPool.contains(item)) {
65                throw new IllegalStateException("Trying to recycle already recycled item");
66            }
67
68            if (itemPool.size() < MAX_POOL_SIZE) {
69                itemPool.add(item);
70            }
71        }
72    }
73}
74