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 private static final String LOG_TAG = "FinitePool"; 24 25 /** 26 * Factory used to create new pool objects 27 */ 28 private final PoolableManager<T> mManager; 29 /** 30 * Maximum number of objects in the pool 31 */ 32 private final int mLimit; 33 /** 34 * If true, mLimit is ignored 35 */ 36 private final boolean mInfinite; 37 38 /** 39 * Next object to acquire 40 */ 41 private T mRoot; 42 /** 43 * Number of objects in the pool 44 */ 45 private int mPoolCount; 46 FinitePool(PoolableManager<T> manager)47 FinitePool(PoolableManager<T> manager) { 48 mManager = manager; 49 mLimit = 0; 50 mInfinite = true; 51 } 52 FinitePool(PoolableManager<T> manager, int limit)53 FinitePool(PoolableManager<T> manager, int limit) { 54 if (limit <= 0) throw new IllegalArgumentException("The pool limit must be > 0"); 55 56 mManager = manager; 57 mLimit = limit; 58 mInfinite = false; 59 } 60 acquire()61 public T acquire() { 62 T element; 63 64 if (mRoot != null) { 65 element = mRoot; 66 mRoot = element.getNextPoolable(); 67 mPoolCount--; 68 } else { 69 element = mManager.newInstance(); 70 } 71 72 if (element != null) { 73 element.setNextPoolable(null); 74 element.setPooled(false); 75 mManager.onAcquired(element); 76 } 77 78 return element; 79 } 80 release(T element)81 public void release(T element) { 82 if (!element.isPooled()) { 83 if (mInfinite || mPoolCount < mLimit) { 84 mPoolCount++; 85 element.setNextPoolable(mRoot); 86 element.setPooled(true); 87 mRoot = element; 88 } 89 mManager.onReleased(element); 90 } else { 91 Log.w(LOG_TAG, "Element is already in pool: " + element); 92 } 93 } 94 } 95