KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jac > util > WeakList


1
2 package org.objectweb.jac.util;
3
4 import java.lang.ref.Reference JavaDoc;
5 import java.lang.ref.ReferenceQueue JavaDoc;
6 import java.lang.ref.WeakReference JavaDoc;
7 import java.util.AbstractList JavaDoc;
8 import java.util.ArrayList JavaDoc;
9 import java.util.List JavaDoc;
10 import org.apache.log4j.Logger;
11
12 public class WeakList extends AbstractList JavaDoc {
13     static Logger logger = Logger.getLogger("weak.collections");
14
15     /**
16      * Reference queue for cleared weak references
17      */

18     private final ReferenceQueue JavaDoc queue = new ReferenceQueue JavaDoc();
19    
20     private final List JavaDoc list=new ArrayList JavaDoc();
21
22     public boolean add(Object JavaDoc o) {
23         expungeStaleEntries();
24         return list.add(new ListEntry(o,queue));
25     }
26
27     public Object JavaDoc get(int i) {
28         expungeStaleEntries();
29         return ((Reference JavaDoc)list.get(i)).get();
30     }
31
32     public int size() {
33         //new Exception().printStackTrace();
34
expungeStaleEntries();
35         return list.size();
36     }
37
38     public Object JavaDoc remove(int index) {
39         return ((ListEntry)list.remove(index)).get();
40     }
41
42     /**
43      * Expunge stale entries from the list.
44      */

45     private void expungeStaleEntries() {
46         Object JavaDoc 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 JavaDoc {
58         String JavaDoc objectString;
59         public ListEntry(Object JavaDoc o,ReferenceQueue JavaDoc queue) {
60             super(o,queue);
61             objectString=o.toString();
62         }
63         public boolean equals(Object JavaDoc 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 JavaDoc 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