• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 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.util;
18 
19 /**
20  * @hide
21  */
22 class FinitePool<T extends Poolable<T>> implements Pool<T> {
23     /**
24      * Factory used to create new pool objects
25      */
26     private final PoolableManager<T> mManager;
27     /**
28      * Maximum number of objects in the pool
29      */
30     private final int mLimit;
31     /**
32      * If true, mLimit is ignored
33      */
34     private final boolean mInfinite;
35 
36     /**
37      * Next object to acquire
38      */
39     private T mRoot;
40     /**
41      * Number of objects in the pool
42      */
43     private int mPoolCount;
44 
FinitePool(PoolableManager<T> manager)45     FinitePool(PoolableManager<T> manager) {
46         mManager = manager;
47         mLimit = 0;
48         mInfinite = true;
49     }
50 
FinitePool(PoolableManager<T> manager, int limit)51     FinitePool(PoolableManager<T> manager, int limit) {
52         if (limit <= 0) throw new IllegalArgumentException("The pool limit must be > 0");
53 
54         mManager = manager;
55         mLimit = limit;
56         mInfinite = false;
57     }
58 
acquire()59     public T acquire() {
60         T element;
61 
62         if (mRoot != null) {
63             element = mRoot;
64             mRoot = element.getNextPoolable();
65             mPoolCount--;
66         } else {
67             element = mManager.newInstance();
68         }
69 
70         if (element != null) {
71             element.setNextPoolable(null);
72             mManager.onAcquired(element);
73         }
74 
75         return element;
76     }
77 
release(T element)78     public void release(T element) {
79         if (mInfinite || mPoolCount < mLimit) {
80             mPoolCount++;
81             element.setNextPoolable(mRoot);
82             mRoot = element;
83         }
84         mManager.onReleased(element);
85     }
86 }
87