1 9 10 package org.jboss.aop.util; 11 12 import java.lang.ref.ReferenceQueue ; 13 import java.lang.ref.SoftReference ; 14 import java.util.AbstractMap ; 15 import java.util.HashMap ; 16 import java.util.Map ; 17 import java.util.Set ; 18 19 20 27 public class SoftValueHashMap 28 extends AbstractMap 29 implements Map 30 { 31 private static class SoftValueRef extends SoftReference 32 { 33 public Object key; 34 35 private SoftValueRef(Object key, Object val, ReferenceQueue q) 36 { 37 super(val, q); 38 this.key = key; 39 } 40 41 private static SoftValueRef create(Object key, Object val, ReferenceQueue q) 42 { 43 if (val == null) return null; 44 else return new SoftValueRef(key, val, q); 45 } 46 47 } 48 public Set entrySet() 49 { 50 processQueue(); 51 return hash.entrySet(); 52 } 53 54 55 private Map hash; 56 57 58 private ReferenceQueue queue = new ReferenceQueue (); 59 60 63 private void processQueue() 64 { 65 SoftValueRef ref; 66 while ((ref = (SoftValueRef)queue.poll()) != null) { 67 if (ref == (SoftValueRef) hash.get(ref.key)) { 68 hash.remove(ref.key); 71 } 72 } 73 } 74 75 76 77 78 91 public SoftValueHashMap(int initialCapacity, float loadFactor) 92 { 93 hash = new HashMap (initialCapacity, loadFactor); 94 } 95 96 107 public SoftValueHashMap(int initialCapacity) 108 { 109 hash = new HashMap (initialCapacity); 110 } 111 112 117 public SoftValueHashMap() 118 { 119 hash = new HashMap (); 120 } 121 122 132 public SoftValueHashMap(Map t) 133 { 134 this(Math.max(2*t.size(), 11), 0.75f); 135 putAll(t); 136 } 137 138 139 140 146 public int size() 147 { 148 processQueue(); 149 return hash.size(); 150 } 151 152 155 public boolean isEmpty() 156 { 157 processQueue(); 158 return hash.isEmpty(); 159 } 160 161 167 public boolean containsKey(Object key) 168 { 169 processQueue(); 170 return hash.containsKey(key); 171 } 172 173 174 175 182 public Object get(Object key) 183 { 184 processQueue(); 185 SoftReference ref = (SoftReference )hash.get(key); 186 if (ref != null) return ref.get(); 187 return null; 188 } 189 190 204 public Object put(Object key, Object value) 205 { 206 processQueue(); 207 Object rtn = hash.put(key, SoftValueRef.create(key, value, queue)); 208 if (rtn != null) rtn = ((SoftReference )rtn).get(); 209 return rtn; 210 } 211 212 221 public Object remove(Object key) 222 { 223 processQueue(); 224 return hash.remove(key); 225 } 226 227 230 public void clear() 231 { 232 processQueue(); 233 hash.clear(); 234 } 235 } 236 | Popular Tags |