2 * Copyright (C) 2008 Esmertec AG.
3 * Copyright (C) 2008 The Android Open Source Project
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package com.google.android.mms.util;
20 import android.util.Config;
21 import android.util.Log;
23 import java.util.HashMap;
25 public abstract class AbstractCache<K, V> {
26 private static final String TAG = "AbstractCache";
27 private static final boolean DEBUG = false;
28 private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
30 private static final int MAX_CACHED_ITEMS = 500;
32 private final HashMap<K, CacheEntry<V>> mCacheMap;
34 protected AbstractCache() {
35 mCacheMap = new HashMap<K, CacheEntry<V>>();
38 public boolean put(K key, V value) {
40 Log.v(TAG, "Trying to put " + key + " into cache.");
43 if (mCacheMap.size() >= MAX_CACHED_ITEMS) {
44 // TODO Should remove the oldest or least hit cached entry
45 // and then cache the new one.
47 Log.v(TAG, "Failed! size limitation reached.");
53 CacheEntry<V> cacheEntry = new CacheEntry<V>();
54 cacheEntry.value = value;
55 mCacheMap.put(key, cacheEntry);
58 Log.v(TAG, key + " cached, " + mCacheMap.size() + " items total.");
67 Log.v(TAG, "Trying to get " + key + " from cache.");
71 CacheEntry<V> cacheEntry = mCacheMap.get(key);
72 if (cacheEntry != null) {
75 Log.v(TAG, key + " hit " + cacheEntry.hit + " times.");
77 return cacheEntry.value;
83 public V purge(K key) {
85 Log.v(TAG, "Trying to purge " + key);
88 CacheEntry<V> v = mCacheMap.remove(key);
91 Log.v(TAG, mCacheMap.size() + " items cached.");
94 return v != null ? v.value : null;
97 public void purgeAll() {
99 Log.v(TAG, "Purging cache, " + mCacheMap.size()
100 + " items dropped.");
106 return mCacheMap.size();
109 private static class CacheEntry<V> {