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 com.android.camera.gallery;
18 
19 import java.lang.ref.ReferenceQueue;
20 import java.lang.ref.WeakReference;
21 import java.util.HashMap;
22 import java.util.LinkedHashMap;
23 import java.util.Map;
24 
25 public class LruCache<K, V> {
26 
27     private final HashMap<K, V> mLruMap;
28     private final HashMap<K, Entry<K, V>> mWeakMap =
29             new HashMap<K, Entry<K, V>>();
30     private ReferenceQueue<V> mQueue = new ReferenceQueue<V>();
31 
32     @SuppressWarnings("serial")
LruCache(final int capacity)33     public LruCache(final int capacity) {
34         mLruMap = new LinkedHashMap<K, V>(16, 0.75f, true) {
35             @Override
36             protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
37                 return size() > capacity;
38             }
39         };
40     }
41 
42     private static class Entry<K, V> extends WeakReference<V> {
43         K mKey;
44 
Entry(K key, V value, ReferenceQueue<V> queue)45         public Entry(K key, V value, ReferenceQueue<V> queue) {
46             super(value, queue);
47             mKey = key;
48         }
49     }
50 
51     @SuppressWarnings("unchecked")
cleanUpWeakMap()52     private void cleanUpWeakMap() {
53         Entry<K, V> entry = (Entry<K, V>) mQueue.poll();
54         while (entry != null) {
55             mWeakMap.remove(entry.mKey);
56             entry = (Entry<K, V>) mQueue.poll();
57         }
58     }
59 
put(K key, V value)60     public synchronized V put(K key, V value) {
61         cleanUpWeakMap();
62         mLruMap.put(key, value);
63         Entry<K, V> entry = mWeakMap.put(
64                 key, new Entry<K, V>(key, value, mQueue));
65         return entry == null ? null : entry.get();
66     }
67 
get(K key)68     public synchronized V get(K key) {
69         cleanUpWeakMap();
70         V value = mLruMap.get(key);
71         if (value != null) return value;
72         Entry<K, V> entry = mWeakMap.get(key);
73         return entry == null ? null : entry.get();
74     }
75 
clear()76     public synchronized void clear() {
77         mLruMap.clear();
78         mWeakMap.clear();
79         mQueue = new ReferenceQueue<V>();
80     }
81 }
82