IdentityCache.java revision f9a0a4306d589b4a4e20554fed512a603426bfa1
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
17package com.android.gallery3d.util;
18
19import java.lang.ref.ReferenceQueue;
20import java.lang.ref.WeakReference;
21import java.util.HashMap;
22import java.util.ArrayList;
23import java.util.Set;
24
25public 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
31    public IdentityCache() {
32    }
33
34    private static class Entry<K, V> extends WeakReference<V> {
35        K mKey;
36
37        public Entry(K key, V value, ReferenceQueue<V> queue) {
38            super(value, queue);
39            mKey = key;
40        }
41    }
42
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
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
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    public synchronized void clear() {
65        mWeakMap.clear();
66        mQueue = new ReferenceQueue<V>();
67    }
68
69    public synchronized ArrayList<K> keys() {
70        Set<K> set = mWeakMap.keySet();
71        ArrayList<K> result = new ArrayList<K>(set);
72        return result;
73    }
74}
75