blob: 3edc424a385c625a12d9ac790ab2cc7ea19701e8 [file] [log] [blame]
Owen Lina2fba682011-08-17 22:07:43 +08001/*
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;
Owen Lina2fba682011-08-17 22:07:43 +080021import java.util.ArrayList;
Owen Lin73a04ff2012-03-14 17:27:24 +080022import java.util.HashMap;
Owen Lina2fba682011-08-17 22:07:43 +080023import 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
Chih-Chung Chang980724b2012-02-22 08:00:31 +080064 // This is currently unused.
65 /*
Owen Lina2fba682011-08-17 22:07:43 +080066 public synchronized void clear() {
67 mWeakMap.clear();
68 mQueue = new ReferenceQueue<V>();
69 }
Chih-Chung Chang980724b2012-02-22 08:00:31 +080070 */
Owen Lina2fba682011-08-17 22:07:43 +080071
Chih-Chung Chang980724b2012-02-22 08:00:31 +080072 // This is for debugging only
Owen Lina2fba682011-08-17 22:07:43 +080073 public synchronized ArrayList<K> keys() {
74 Set<K> set = mWeakMap.keySet();
75 ArrayList<K> result = new ArrayList<K>(set);
76 return result;
77 }
78}