1 2 package org.objectweb.jac.util; 3 4 import java.lang.ref.Reference ; 5 import java.lang.ref.ReferenceQueue ; 6 import java.lang.ref.WeakReference ; 7 import java.util.AbstractList ; 8 import java.util.ArrayList ; 9 import java.util.List ; 10 import org.apache.log4j.Logger; 11 12 public class WeakList extends AbstractList { 13 static Logger logger = Logger.getLogger("weak.collections"); 14 15 18 private final ReferenceQueue queue = new ReferenceQueue (); 19 20 private final List list=new ArrayList (); 21 22 public boolean add(Object o) { 23 expungeStaleEntries(); 24 return list.add(new ListEntry(o,queue)); 25 } 26 27 public Object get(int i) { 28 expungeStaleEntries(); 29 return ((Reference )list.get(i)).get(); 30 } 31 32 public int size() { 33 expungeStaleEntries(); 35 return list.size(); 36 } 37 38 public Object remove(int index) { 39 return ((ListEntry)list.remove(index)).get(); 40 } 41 42 45 private void expungeStaleEntries() { 46 Object r; 47 while ( (r = queue.poll()) != null) { 48 ListEntry e = (ListEntry)r; 49 int i=list.indexOf(r); 50 if(i!=-1) { 51 logger.debug("removing from list "+r+" ("+i+")"); 52 list.remove(i); 53 } 54 } 55 } 56 57 private static class ListEntry extends WeakReference { 58 String objectString; 59 public ListEntry(Object o,ReferenceQueue queue) { 60 super(o,queue); 61 objectString=o.toString(); 62 } 63 public boolean equals(Object o) { 64 if(o==null) { 65 return false; 66 } else { 67 if((o instanceof ListEntry)) { 68 return o.hashCode()==this.hashCode(); 69 } else { 70 if(this.get()==null) return false; 71 return this.get().equals(o); 72 } 73 } 74 } 75 public String toString() { 76 if(this.get()==null) { 77 return "'entry "+objectString+" <GARBAGED>'"; 78 } else { 79 return "'entry "+this.get()+"'"; 80 } 81 } 82 83 } 84 } 85 | Popular Tags |