1 22 package org.jboss.util.collection; 23 24 import java.util.Map ; 25 import java.util.AbstractMap ; 26 import java.util.HashMap ; 27 import java.util.Set ; 28 29 import java.lang.ref.WeakReference ; 30 import java.lang.ref.ReferenceQueue ; 31 32 33 40 public class WeakValueHashMap 41 extends AbstractMap 42 implements Map 43 { 44 private static class WeakValueRef extends WeakReference 45 { 46 public Object key; 47 48 private WeakValueRef(Object key, Object val, ReferenceQueue q) 49 { 50 super(val, q); 51 this.key = key; 52 } 53 54 private static WeakValueRef create(Object key, Object val, ReferenceQueue q) 55 { 56 if (val == null) return null; 57 else return new WeakValueRef(key, val, q); 58 } 59 60 } 61 public Set entrySet() 62 { 63 processQueue(); 64 return hash.entrySet(); 65 } 66 67 68 private Map hash; 69 70 71 private ReferenceQueue queue = new ReferenceQueue (); 72 73 76 private void processQueue() 77 { 78 WeakValueRef ref; 79 while ((ref = (WeakValueRef)queue.poll()) != null) { 80 if (ref == (WeakValueRef) hash.get(ref.key)) { 81 hash.remove(ref.key); 84 } 85 } 86 } 87 88 89 90 91 104 public WeakValueHashMap(int initialCapacity, float loadFactor) 105 { 106 hash = new HashMap (initialCapacity, loadFactor); 107 } 108 109 120 public WeakValueHashMap(int initialCapacity) 121 { 122 hash = new HashMap (initialCapacity); 123 } 124 125 130 public WeakValueHashMap() 131 { 132 hash = new HashMap (); 133 } 134 135 145 public WeakValueHashMap(Map t) 146 { 147 this(Math.max(2*t.size(), 11), 0.75f); 148 putAll(t); 149 } 150 151 152 153 159 public int size() 160 { 161 processQueue(); 162 return hash.size(); 163 } 164 165 168 public boolean isEmpty() 169 { 170 processQueue(); 171 return hash.isEmpty(); 172 } 173 174 180 public boolean containsKey(Object key) 181 { 182 processQueue(); 183 return hash.containsKey(key); 184 } 185 186 187 188 195 public Object get(Object key) 196 { 197 processQueue(); 198 WeakReference ref = (WeakReference )hash.get(key); 199 if (ref != null) return ref.get(); 200 return null; 201 } 202 203 217 public Object put(Object key, Object value) 218 { 219 processQueue(); 220 Object rtn = hash.put(key, WeakValueRef.create(key, value, queue)); 221 if (rtn != null) rtn = ((WeakReference )rtn).get(); 222 return rtn; 223 } 224 225 234 public Object remove(Object key) 235 { 236 processQueue(); 237 return hash.remove(key); 238 } 239 240 243 public void clear() 244 { 245 processQueue(); 246 hash.clear(); 247 } 248 } 249 | Popular Tags |