1 24 package org.riotfamily.common.collection; 25 26 import java.lang.ref.Reference ; 27 import java.lang.ref.WeakReference ; 28 import java.util.AbstractCollection ; 29 import java.util.ArrayList ; 30 import java.util.Collection ; 31 import java.util.Iterator ; 32 33 import org.apache.commons.logging.Log; 34 import org.apache.commons.logging.LogFactory; 35 36 42 public class WeakReferenceCollection extends AbstractCollection { 43 44 private static final Log log = LogFactory 45 .getLog(WeakReferenceCollection.class); 46 47 private Collection references = new ArrayList (); 48 49 52 public Iterator iterator() { 53 return new ReferentIterator(); 54 } 55 56 61 public int size() { 62 return references.size(); 63 } 64 65 69 public boolean add(Object value) { 70 references.add(new WeakReference (value)); 71 return true; 72 } 73 74 77 public void clear() { 78 references.clear(); 79 } 80 81 84 public void purge() { 85 Iterator it = iterator(); 86 while (it.hasNext()) { 87 it.next(); 88 } 89 } 90 91 private class ReferentIterator implements Iterator { 92 93 private Iterator it = references.iterator(); 94 95 private Object nextValue = null; 96 97 public boolean hasNext() { 98 while (it.hasNext()) { 99 Reference ref = (Reference ) it.next(); 100 nextValue = ref.get(); 101 if (nextValue == null) { 102 log.debug("Item cleared, removing reference."); 103 it.remove(); 104 } 105 else { 106 return true; 107 } 108 } 109 return false; 110 } 111 112 public Object next() { 113 return nextValue; 114 } 115 116 public void remove() { 117 it.remove(); 118 } 119 120 } 121 } 122 | Popular Tags |