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