1 19 package org.netbeans.modules.javacore.jmiimpl.javamodel; 20 21 import java.lang.ref.ReferenceQueue ; 22 import java.lang.ref.WeakReference ; 23 import java.lang.ref.Reference ; 24 import java.util.ArrayList ; 25 import java.util.Collection ; 26 import java.util.HashMap ; 27 import java.util.Iterator ; 28 29 33 public class InstanceMap extends HashMap { 34 private final ReferenceQueue queue = new ReferenceQueue (); 35 36 private class InstanceReference extends WeakReference { 37 private Object key; 38 39 public InstanceReference(Object key, Object instance) { 40 super(instance, queue); 41 this.key = key; 42 } 43 44 public Object getKey() { 45 return key; 46 } 47 } 48 49 private void cleanUp() { 50 InstanceReference reference; 51 52 while ((reference = (InstanceReference) queue.poll()) != null) { 53 Object key = reference.getKey(); 54 Reference currentRef = (Reference ) super.remove(key); 55 if (currentRef != null && currentRef != reference && currentRef.get() != null) { 56 super.put(key, currentRef); 57 } 58 } 59 } 60 61 public Object put(Object key, Object value) { 62 cleanUp(); 63 Object result = super.put(key, new InstanceReference(key, value)); 64 if (result != null) { 65 return ((InstanceReference) result).get(); 66 } else { 67 return result; 68 } 69 } 70 71 public Object get(Object key) { 72 cleanUp(); 73 Object result = super.get(key); 74 if (result != null) { 75 return ((InstanceReference) result).get(); 76 } else { 77 return result; 78 } 79 } 80 81 public Collection values() { 82 ArrayList result = new ArrayList (); 83 cleanUp(); 84 for (Iterator it = super.values().iterator(); it.hasNext();) { 85 result.add(((InstanceReference) it.next()).get()); 86 } 87 return result; 88 } 89 } 90 | Popular Tags |