1 23 24 package com.sun.jdo.spi.persistence.utility; 25 26 import java.util.*; 27 import java.lang.ref.*; 28 29 33 public class WeakHashSet 34 extends HashSet 35 { 36 39 ReferenceQueue queue = new ReferenceQueue(); 40 41 47 public Iterator iterator () 48 { 49 processQueue(); 51 52 final Iterator i = super.iterator(); 54 55 return new Iterator () { 56 public boolean hasNext () 57 { 58 return i.hasNext(); 59 } 60 61 public Object next () 62 { 63 return getReferenceObject((WeakReference)i.next()); 65 } 66 67 public void remove () 68 { 69 i.remove(); 71 } 72 }; 73 } 74 75 81 public boolean contains (Object o) 82 { 83 return super.contains(WeakElement.create(o)); 84 } 85 86 94 public boolean add (Object o) 95 { 96 processQueue(); 97 return super.add(WeakElement.create(o, this.queue)); 98 } 99 100 106 public boolean remove (Object o) 107 { 108 boolean ret = super.remove(WeakElement.create(o)); 109 processQueue(); 110 return ret; 111 } 112 113 117 private final Object getReferenceObject (WeakReference ref) 118 { 119 return ((ref != null) ? ref.get() : null); 120 } 121 122 127 private final void processQueue () 128 { 129 WeakElement wv = null; 130 131 while ((wv = (WeakElement)this.queue.poll()) != null) 132 { 133 super.remove(wv); 134 } 135 } 136 137 144 static private class WeakElement 145 extends WeakReference 146 { 147 private int hash; 149 150 private WeakElement (Object o) 151 { 152 super(o); 153 hash = o.hashCode(); 154 } 155 156 private WeakElement (Object o, ReferenceQueue q) 157 { 158 super(o, q); 159 hash = o.hashCode(); 160 } 161 162 private static WeakElement create (Object o) 163 { 164 return (o == null) ? null : new WeakElement(o); 165 } 166 167 private static WeakElement create (Object o, ReferenceQueue q) 168 { 169 return (o == null) ? null : new WeakElement(o, q); 170 } 171 172 174 public boolean equals (Object o) 175 { 176 if (this == o) 177 return true; 178 if (!(o instanceof WeakElement)) 179 return false; 180 Object t = this.get(); 181 Object u = ((WeakElement)o).get(); 182 if ((t == null) || (u == null)) 183 return false; 184 if (t == u) 185 return true; 186 return t.equals(u); 187 } 188 189 public int hashCode () 190 { 191 return hash; 192 } 193 194 } 195 196 } 197 198 | Popular Tags |