1 9 package mondrian.rolap.cache; 10 11 import java.lang.ref.ReferenceQueue ; 12 import java.lang.ref.SoftReference ; 13 import java.util.HashMap ; 14 import java.util.Map ; 15 16 28 public class SoftSmartCache <K, V> implements SmartCache <K, V> { 29 30 Map <K, CacheReference> cache = new HashMap <K, CacheReference>(); 31 ReferenceQueue <V> queue = new ReferenceQueue <V>(); 32 33 41 class CacheReference extends SoftReference <V> { 42 K key; 43 44 public CacheReference(K key, V value) { 45 super(value, queue); 46 this.key = key; 47 } 48 49 public String toString() { 50 return String.valueOf(get()); 51 } 52 } 53 54 57 public synchronized V put(K key, V value) { 58 CacheReference ref; 60 while ((ref = (CacheReference) queue.poll()) != null) { 61 cache.remove(ref.key); 62 } 63 64 ref = new CacheReference(key, value); 66 ref = cache.put(key, ref); 67 if (ref != null) { 68 return ref.get(); 69 } 70 return null; 71 } 72 73 76 public synchronized V get(K key) { 77 CacheReference ref = cache.get(key); 78 if (ref == null) { 79 return null; 80 } 81 V value = ref.get(); 82 if (value == null) { 83 cache.remove(key); 84 } 85 return value; 86 } 87 88 91 public void clear() { 92 cache.clear(); 93 } 94 95 98 public int size() { 99 return cache.size(); 100 } 101 102 } 103 104 106 | Popular Tags |