1 package dynaop.util; 2 3 import java.lang.ref.Reference ; 4 import java.lang.ref.ReferenceQueue ; 5 import java.lang.ref.SoftReference ; 6 import java.lang.ref.WeakReference ; 7 import java.util.Collections ; 8 import java.util.HashMap ; 9 import java.util.Map ; 10 import java.util.WeakHashMap ; 11 12 17 public abstract class Cache { 18 19 static Object NULL_VALUE = new Object (); 20 21 Map map; 22 ReferenceQueue queue = new ReferenceQueue (); 23 24 29 public Cache(boolean weakKeys) { 30 this.map = (weakKeys) ? 31 (Map ) new WeakHashMap () : new HashMap (); 32 this.map = Collections.synchronizedMap(this.map); 33 } 34 35 38 public Cache() { 39 this(true); 40 } 41 42 46 protected abstract Object create(Object key); 47 48 51 public Object get(Object key) { 52 Object value = internalGet(key); 53 if (value == null) { 54 value = create(key); 55 if (value == null) 56 value = NULL_VALUE; 57 this.map.put(key, 58 new ValueReference(key, value)); 59 } 60 return (value == NULL_VALUE) ? null : value; 61 } 62 63 void cleanUp() { 64 Reference reference; 65 while ((reference = this.queue.poll()) != null) 66 map.remove( 67 ((ValueReference) reference).getKey()); 68 } 69 70 Object internalGet(Object key) { 71 cleanUp(); 72 Reference reference = (Reference ) map.get(key); 73 return (reference == null) ? 74 null : reference.get(); 75 } 76 77 class ValueReference extends SoftReference { 78 79 WeakReference keyReference; 80 81 ValueReference(Object key, Object value) { 82 super(value, queue); 83 this.keyReference = new WeakReference (key); 84 } 85 86 Object getKey() { 87 return this.keyReference.get(); 88 } 89 } 90 } 91 | Popular Tags |