001: /*
002: * WeakValueMap.java created on 31.10.2006
003: *
004: * To change this generated comment go to
005: * Window>Preferences>Java>Code Generation>Code and Comments
006: */
007: package org.codehaus.groovy.runtime;
008:
009: import java.lang.ref.ReferenceQueue;
010: import java.lang.ref.SoftReference;
011: import java.util.ArrayList;
012: import java.util.Collection;
013: import java.util.Iterator;
014: import java.util.Set;
015: import java.util.WeakHashMap;
016:
017: public class ReferenceMap extends WeakHashMap {
018:
019: private static class HardReference extends SoftReference {
020: private Object value;
021:
022: public HardReference(Object arg) {
023: super (null);
024: value = arg;
025: }
026:
027: public Object get() {
028: return value;
029: }
030: }
031:
032: private ReferenceQueue queue = new ReferenceQueue();
033:
034: public ReferenceMap() {
035: super ();
036: }
037:
038: public boolean containsValue(Object value) {
039: throw new UnsupportedOperationException();
040: }
041:
042: public Set entrySet() {
043: throw new UnsupportedOperationException();
044: }
045:
046: public Object get(Object key) {
047: Object ret = super .get(key);
048: if (ret != null) {
049: SoftReference weak = (SoftReference) ret;
050: ret = weak.get();
051: if (ret == null)
052: remove(key);
053: }
054: return ret;
055: }
056:
057: public Object put(Object key, Object value) {
058: removeDereferencedEntries();
059: if (value != null) {
060: value = new SoftReference(value, queue);
061: }
062: return super .put(key, value);
063: }
064:
065: public Object putStrong(Object key, Object value) {
066: removeDereferencedEntries();
067: if (value != null) {
068: value = new HardReference(value);
069: }
070: return super .put(key, value);
071: }
072:
073: public Collection values() {
074: removeDereferencedEntries();
075: Collection origColl = super .values();
076: ArrayList newColl = new ArrayList(origColl.size());
077: for (Iterator iter = origColl.iterator(); iter.hasNext();) {
078: SoftReference element = (SoftReference) iter.next();
079: if (element != null) {
080: Object strong = element.get();
081: if (strong == null)
082: continue;
083: newColl.add(strong);
084: } else {
085: newColl.add(null);
086: }
087: }
088: return newColl;
089: }
090:
091: private void removeDereferencedEntries() {
092: SoftReference e;
093: while ((e = (SoftReference) queue.poll()) != null) {
094: Object strong = e.get();
095: if (strong == null)
096: continue;
097: remove(strong);
098: }
099: }
100: }
|