1 52 53 package freemarker.cache; 54 55 import java.lang.ref.Reference ; 56 import java.lang.ref.ReferenceQueue ; 57 import java.lang.ref.SoftReference ; 58 import java.util.HashMap ; 59 import java.util.Map ; 60 61 75 public class SoftCacheStorage implements CacheStorage 76 { 77 private final ReferenceQueue queue = new ReferenceQueue (); 78 private final Map map; 79 80 public SoftCacheStorage() 81 { 82 this(new HashMap ()); 83 } 84 85 public SoftCacheStorage(Map backingMap) 86 { 87 this.map = backingMap; 88 } 89 90 public Object get(Object key) 91 { 92 processQueue(); 93 Reference ref = (Reference )map.get(key); 94 return ref == null ? null : ref.get(); 95 } 96 97 public void put(Object key, Object value) 98 { 99 processQueue(); 100 map.put(key, new SoftValueReference(key, value, queue)); 101 } 102 103 public void remove(Object key) 104 { 105 processQueue(); 106 map.remove(key); 107 } 108 109 public void clear() 110 { 111 map.clear(); 112 processQueue(); 113 } 114 115 private void processQueue() 116 { 117 for(;;) 118 { 119 SoftValueReference ref = (SoftValueReference)queue.poll(); 120 if(ref == null) 121 { 122 return; 123 } 124 Object key = ref.getKey(); 125 if(map.get(key) == ref) 128 { 129 map.remove(key); 130 } 131 } 132 } 133 134 private static final class SoftValueReference 135 extends 136 SoftReference 137 { 138 private final Object key; 139 140 SoftValueReference(Object key, Object value, ReferenceQueue queue) 141 { 142 super(value, queue); 143 this.key = key; 144 } 145 146 Object getKey() 147 { 148 return key; 149 } 150 } 151 } 152 | Popular Tags |