1 /*
2  * Copyright (C) 2010 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.gallery3d.util;
18 
19 import java.lang.ref.ReferenceQueue;
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.Set;
24 
25 public class IdentityCache<K, V> {
26 
27     private final HashMap<K, Entry<K, V>> mWeakMap =
28             new HashMap<K, Entry<K, V>>();
29     private ReferenceQueue<V> mQueue = new ReferenceQueue<V>();
30 
IdentityCache()31     public IdentityCache() {
32     }
33 
34     private static class Entry<K, V> extends WeakReference<V> {
35         K mKey;
36 
Entry(K key, V value, ReferenceQueue<V> queue)37         public Entry(K key, V value, ReferenceQueue<V> queue) {
38             super(value, queue);
39             mKey = key;
40         }
41     }
42 
cleanUpWeakMap()43     private void cleanUpWeakMap() {
44         Entry<K, V> entry = (Entry<K, V>) mQueue.poll();
45         while (entry != null) {
46             mWeakMap.remove(entry.mKey);
47             entry = (Entry<K, V>) mQueue.poll();
48         }
49     }
50 
put(K key, V value)51     public synchronized V put(K key, V value) {
52         cleanUpWeakMap();
53         Entry<K, V> entry = mWeakMap.put(
54                 key, new Entry<K, V>(key, value, mQueue));
55         return entry == null ? null : entry.get();
56     }
57 
get(K key)58     public synchronized V get(K key) {
59         cleanUpWeakMap();
60         Entry<K, V> entry = mWeakMap.get(key);
61         return entry == null ? null : entry.get();
62     }
63 
64     // This is currently unused.
65     /*
66     public synchronized void clear() {
67         mWeakMap.clear();
68         mQueue = new ReferenceQueue<V>();
69     }
70     */
71 
72     // This is for debugging only
keys()73     public synchronized ArrayList<K> keys() {
74         Set<K> set = mWeakMap.keySet();
75         ArrayList<K> result = new ArrayList<K>(set);
76         return result;
77     }
78 }
79