/*
* Copyright 2002-2006 (C) TJDO.
* All rights reserved.
*
* This software is distributed under the terms of the TJDO License version 1.0.
* See the terms of the TJDO License in the documentation provided with this software.
*
* $Id: ReferenceValueMap.java,v 1.8 2006/09/08 16:11:28 jackknifebarber Exp $
*/
import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set;
/*
* Copyright 2002-2006 (C) TJDO.
* All rights reserved.
*
* This software is distributed under the terms of the TJDO License version 1.0.
* See the terms of the TJDO License in the documentation provided with this software.
*
* $Id: SoftValueMap.java,v 1.5 2006/09/08 16:11:28 jackknifebarber Exp $
*/
/**
* A <code>java.util.Map</code> implementation with soft values.
* <p>
* The values are stored as soft references.
* If map entry value object is not actively being used, i.e. no other object
* has a strong reference to it, it may become garbage collected at the
* discretion of the garbage collector (typically if the VM is low on memory).
* If this happens, the entry in the <code>SoftValueMap</code> corresponding to
* the value object will also be removed.
*
* @author <a href="mailto:[email protected]">Mike Martin</a>
* @version $Revision: 1.5 $
*
* @see SoftReference
*/
public class SoftValueMap extends ReferenceValueMap
{ public SoftValueMap()
{ super(new HashMap());
}
public SoftValueMap(int initialCapacity)
{ super(new HashMap(initialCapacity));
}
public SoftValueMap(int initialCapacity, float loadFactor)
{ super(new HashMap(initialCapacity, loadFactor));
}
public SoftValueMap(Map m)
{ super(new HashMap(m));
}
/**
* A <code>java.util.Map</code> implementation using reference values.
* <p>
* The values are stored in the map as references.
* If the garbage collector clears the reference, the corresponding key is
* automatically removed from the map.
*
* @author <a href="mailto:[email protected]">Mike Martin</a>
* @version $Revision: 1.8 $
*/
abstract class ReferenceValueMap extends AbstractMap
{ protected final ReferenceQueue refQueue = new ReferenceQueue();
/** Backing map. */ private final Map backing;
/**
* Returns a new <code>Reference</code> object to be inserted into the map.
* Subclasses must implement this method to construct <code>Reference</code>
* objects of the desired type (e.g. <code>SoftReference</code>, etc.).
*
* @param value
* The associated value to be referenced.
*
* @return
* A new <code>Reference</code> object to be inserted into the map.
*/ protected abstract Reference newReference(Object value);
private void reap()
{
Reference ref;
while ((ref = refQueue.poll()) != null)
backing.values().remove(ref);
}