1 7 8 package com.sun.jmx.mbeanserver; 9 10 import static com.sun.jmx.mbeanserver.Util.*; 11 12 import java.lang.ref.Reference ; 13 import java.lang.ref.ReferenceQueue ; 14 import java.lang.ref.WeakReference ; 15 16 import java.util.Map ; 17 18 19 33 41 class WeakIdentityHashMap<K, V> { 42 private WeakIdentityHashMap() {} 43 44 static <K, V> WeakIdentityHashMap<K, V> make() { 45 return new WeakIdentityHashMap<K, V>(); 46 } 47 48 V get(K key) { 49 expunge(); 50 WeakReference <K> keyref = makeReference(key); 51 return map.get(keyref); 52 } 53 54 public V put(K key, V value) { 55 expunge(); 56 if (key == null) 57 throw new IllegalArgumentException ("Null key"); 58 WeakReference <K> keyref = makeReference(key, refQueue); 59 return map.put(keyref, value); 60 } 61 62 public V remove(K key) { 63 expunge(); 64 WeakReference <K> keyref = makeReference(key); 65 return map.remove(keyref); 66 } 67 68 private void expunge() { 69 Reference <? extends K> ref; 70 while ((ref = refQueue.poll()) != null) 71 map.remove(ref); 72 } 73 74 private WeakReference <K> makeReference(K referent) { 75 return new IdentityWeakReference<K>(referent); 76 } 77 78 private WeakReference <K> makeReference(K referent, ReferenceQueue <K> q) { 79 return new IdentityWeakReference<K>(referent, q); 80 } 81 82 90 private static class IdentityWeakReference<T> extends WeakReference <T> { 91 IdentityWeakReference(T o) { 92 this(o, null); 93 } 94 95 IdentityWeakReference(T o, ReferenceQueue <T> q) { 96 super(o, q); 97 this.hashCode = (o == null) ? 0 : System.identityHashCode(o); 98 } 99 100 public boolean equals(Object o) { 101 if (this == o) 102 return true; 103 if (!(o instanceof IdentityWeakReference)) 104 return false; 105 IdentityWeakReference wr = (IdentityWeakReference) o; 106 Object got = get(); 107 return (got != null && got == wr.get()); 108 } 109 110 public int hashCode() { 111 return hashCode; 112 } 113 114 private final int hashCode; 115 } 116 117 private Map <WeakReference <K>, V> map = newMap(); 118 private ReferenceQueue <K> refQueue = new ReferenceQueue <K>(); 119 } 120 | Popular Tags |