1 22 package org.jboss.util.collection; 23 24 import java.util.Collection ; 25 import java.util.AbstractCollection ; 26 import java.util.Iterator ; 27 28 import java.lang.ref.ReferenceQueue ; 29 30 import org.jboss.util.SoftObject; 31 import org.jboss.util.Objects; 32 33 41 public class CachedCollection 42 extends AbstractCollection 43 { 44 45 protected final ReferenceQueue queue = new ReferenceQueue (); 46 47 48 protected final Collection collection; 49 50 55 public CachedCollection(final Collection collection) { 56 this.collection = collection; 57 } 58 59 64 public Iterator iterator() { 65 maintain(); 66 return new MyIterator(collection.iterator()); 67 } 68 69 74 public int size() { 75 maintain(); 76 return collection.size(); 77 } 78 79 85 public boolean add(final Object obj) { 86 maintain(); 87 88 SoftObject soft = SoftObject.create(obj, queue); 89 90 return collection.add(soft); 91 } 92 93 96 private void maintain() { 97 SoftObject obj; 98 int count = 0; 99 100 while ((obj = (SoftObject)queue.poll()) != null) { 101 count++; 102 collection.remove(obj); 103 } 104 105 if (count != 0) { 106 System.err.println("vm reclaimed " + count + " objects"); 108 } 109 } 110 111 112 116 119 private final class MyIterator 120 implements Iterator 121 { 122 private final Iterator iter; 123 124 public MyIterator(final Iterator iter) { 125 this.iter = iter; 126 } 127 128 public boolean hasNext() { 129 maintain(); 130 return iter.hasNext(); 131 } 132 133 private Object nextObject() { 134 Object obj = iter.next(); 135 136 return Objects.deref(obj); 137 } 138 139 public Object next() { 140 maintain(); 141 return nextObject(); 142 } 143 144 public void remove() { 145 maintain(); 146 iter.remove(); 147 } 148 } 149 } 150 | Popular Tags |