1 /* 2 * Copyright (C) 2008 Esmertec AG. 3 * Copyright (C) 2008 The Android Open Source Project 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package com.android.messaging.mmslib.util; 19 20 import android.support.v4.util.SimpleArrayMap; 21 import android.util.Log; 22 23 public abstract class AbstractCache<K, V> { 24 private static final String TAG = "AbstractCache"; 25 private static final boolean LOCAL_LOGV = false; 26 27 private static final int MAX_CACHED_ITEMS = 500; 28 29 private final SimpleArrayMap<K, CacheEntry<V>> mCacheMap; 30 AbstractCache()31 protected AbstractCache() { 32 mCacheMap = new SimpleArrayMap<K, CacheEntry<V>>(); 33 } 34 put(K key, V value)35 public boolean put(K key, V value) { 36 if (LOCAL_LOGV) { 37 Log.v(TAG, "Trying to put " + key + " into cache."); 38 } 39 40 if (mCacheMap.size() >= MAX_CACHED_ITEMS) { 41 // TODO: Should remove the oldest or least hit cached entry 42 // and then cache the new one. 43 if (LOCAL_LOGV) { 44 Log.v(TAG, "Failed! size limitation reached."); 45 } 46 return false; 47 } 48 49 if (key != null) { 50 CacheEntry<V> cacheEntry = new CacheEntry<V>(); 51 cacheEntry.value = value; 52 mCacheMap.put(key, cacheEntry); 53 54 if (LOCAL_LOGV) { 55 Log.v(TAG, key + " cached, " + mCacheMap.size() + " items total."); 56 } 57 return true; 58 } 59 return false; 60 } 61 get(K key)62 public V get(K key) { 63 if (LOCAL_LOGV) { 64 Log.v(TAG, "Trying to get " + key + " from cache."); 65 } 66 67 if (key != null) { 68 CacheEntry<V> cacheEntry = mCacheMap.get(key); 69 if (cacheEntry != null) { 70 cacheEntry.hit++; 71 if (LOCAL_LOGV) { 72 Log.v(TAG, key + " hit " + cacheEntry.hit + " times."); 73 } 74 return cacheEntry.value; 75 } 76 } 77 return null; 78 } 79 purge(K key)80 public V purge(K key) { 81 if (LOCAL_LOGV) { 82 Log.v(TAG, "Trying to purge " + key); 83 } 84 85 CacheEntry<V> v = mCacheMap.remove(key); 86 87 if (LOCAL_LOGV) { 88 Log.v(TAG, mCacheMap.size() + " items cached."); 89 } 90 91 return v != null ? v.value : null; 92 } 93 purgeAll()94 public void purgeAll() { 95 if (LOCAL_LOGV) { 96 Log.v(TAG, "Purging cache, " + mCacheMap.size() 97 + " items dropped."); 98 } 99 mCacheMap.clear(); 100 } 101 size()102 public int size() { 103 return mCacheMap.size(); 104 } 105 106 private static class CacheEntry<V> { 107 108 int hit; 109 110 V value; 111 } 112 } 113