Top Description Inners Fields Constructors Methods
org.glassfish.pfl.basic.concurrent

public Class SoftCache<K, V>

extends AbstractMap<K, V>
implements Map<K, V>
Class Inheritance
All Implemented Interfaces
java.util.Map
Imports
java.lang.ref.ReferenceQueue, .SoftReference, java.util.AbstractMap, .AbstractSet, .HashMap, .Iterator, .Map, .NoSuchElementException, .Set

A memory-sensitive implementation of the Map interface.

A SoftCache object uses soft references to implement a memory-sensitive hash map. If the garbage collector determines at a certain point in time that a value object in a SoftCache entry is no longer strongly reachable, then it may remove that entry in order to release the memory occupied by the value object. All SoftCache objects are guaranteed to be completely cleared before the virtual machine will throw an OutOfMemoryError. Because of this automatic clearing feature, the behavior of this class is somewhat different from that of other Map implementations.

Both null values and the null key are supported. This class has the same performance characteristics as the HashMap class, and has the same efficiency parameters of initial capacity and load factor.

Like most collection classes, this class is not synchronized. A synchronized SoftCache may be constructed using the Collections.synchronizedMap method.

In typical usage this class will be subclassed and the fill method will be overridden. When the get method is invoked on a key for which there is no mapping in the cache, it will in turn invoke the fill method on that key in an attempt to construct a corresponding value. If the fill method returns such a value then the cache will be updated and the new value will be returned. Thus, for example, a simple URL-content cache can be constructed as follows:

    public class URLCache extends SoftCache {
        protected Object fill(Object key) {
            return ((URL)key).getContent();
        }
    }

The behavior of the SoftCache class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class.

Because entries are removed from a SoftCache in response to dynamic advice from the garbage collector, a SoftCache may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a SoftCache instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value set, and the entry set to yield successively smaller numbers of elements.

I copied this from JDK 1.4.2 to avoid introducing another sun.misc dependency in the ORB. (Ken Cavanaugh)

Author
Mark Reinhold
Since
JDK1.2
Version
1.6, 03/01/23
See Also
java.util.HashMap, java.lang.ref.SoftReference

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
private class
private static class

Field Summary

Modifier and TypeField and Description
private Set<Map.Entry<K, V>>
private Map<K, SoftCache.ValueCell<K, V>>
private static final int
private int
private ReferenceQueue<V>

Constructor Summary

AccessConstructor and Description
public
SoftCache(int
The initial capacity of the cache
initialCapacity
,
float
A number between 0.0 and 1.0
loadFactor
)

Construct a new, empty SoftCache with the given initial capacity and the given load factor.

public
SoftCache(int
The initial capacity of the cache
initialCapacity
)

Construct a new, empty SoftCache with the given initial capacity and the default load factor.

public
SoftCache()

Construct a new, empty SoftCache with the default capacity and the default load factor.

Method Summary

Modifier and TypeMethod and Description
public void
clear()

Overrides java.util.AbstractMap.clear.

Implements java.util.Map.clear.

Remove all mappings from this cache.

public boolean
containsKey(Object
The key whose presence in the cache is to be tested
key
)

Overrides java.util.AbstractMap.containsKey.

Implements java.util.Map.containsKey.

Return true if this cache contains a mapping for the specified key.

public Set<Map.Entry<K, V>>
entrySet()

Implements abstract java.util.AbstractMap.entrySet.

Implements java.util.Map.entrySet.

Return a Set view of the mappings in this cache.

protected V

Returns:

A value for key, or null if one could not be computed
fill
(Object
The key for which a value is to be computed
key
)

Create a value object for the given key.

public V
get(Object
The key whose associated value, if any, is to be returned
key
)

Overrides java.util.AbstractMap.get.

Implements java.util.Map.get.

Return the value to which this cache maps the specified key.

public boolean
isEmpty()

Overrides java.util.AbstractMap.isEmpty.

Implements java.util.Map.isEmpty.

Return true if this cache contains no key-value mappings.

private void
public V

Returns:

The previous value to which this key was mapped, or null if if there was no mapping for the key
put
(K
The key that is to be mapped to the given value
key
,
V
The value to which the given key is to be mapped
value
)

Overrides java.util.AbstractMap.put.

Implements java.util.Map.put.

Update this cache so that the given key maps to the given value.

public V

Returns:

The value to which this key was mapped, or null if there was no mapping for the key
remove
(Object
The key whose mapping is to be removed
key
)

Overrides java.util.AbstractMap.remove.

Implements java.util.Map.remove.

Remove the mapping for the given key from this cache, if present.

public int
size()

Overrides java.util.AbstractMap.size.

Implements java.util.Map.size.

Return the number of key-value mappings in this cache.

private static boolean
Inherited from java.util.AbstractMap:
clonecontainsValueequalshashCodekeySetputAlltoStringvalues

Field Detail

entrySetback to summary
private Set<Map.Entry<K, V>> entrySet
hashback to summary
private Map<K, SoftCache.ValueCell<K, V>> hash
PROCESS_QUEUE_INTERVALback to summary
private static final int PROCESS_QUEUE_INTERVAL
processQueueCountback to summary
private int processQueueCount
queueback to summary
private ReferenceQueue<V> queue

Constructor Detail

SoftCacheback to summary
public SoftCache(int initialCapacity, float loadFactor)

Construct a new, empty SoftCache with the given initial capacity and the given load factor.

Parameters
initialCapacity:int

The initial capacity of the cache

loadFactor:float

A number between 0.0 and 1.0

Exceptions
IllegalArgumentException:
If the initial capacity is less than or equal to zero, or if the load factor is less than zero
SoftCacheback to summary
public SoftCache(int initialCapacity)

Construct a new, empty SoftCache with the given initial capacity and the default load factor.

Parameters
initialCapacity:int

The initial capacity of the cache

Exceptions
IllegalArgumentException:
If the initial capacity is less than or equal to zero
SoftCacheback to summary
public SoftCache()

Construct a new, empty SoftCache with the default capacity and the default load factor.

Method Detail

clearback to summary
public void clear()

Overrides java.util.AbstractMap.clear.

Implements java.util.Map.clear.

Remove all mappings from this cache.

Annotations
@Override
containsKeyback to summary
public boolean containsKey(Object key)

Overrides java.util.AbstractMap.containsKey.

Implements java.util.Map.containsKey.

Return true if this cache contains a mapping for the specified key. If there is no mapping for the key, this method will not attempt to construct one by invoking the fill method.

Parameters
key:Object

The key whose presence in the cache is to be tested

Annotations
@Override
@SuppressWarnings:unchecked
entrySetback to summary
public Set<Map.Entry<K, V>> entrySet()

Implements abstract java.util.AbstractMap.entrySet.

Implements java.util.Map.entrySet.

Return a Set view of the mappings in this cache.

Annotations
@Override
fillback to summary
protected V fill(Object key)

Create a value object for the given key. This method is invoked by the get method when there is no entry for key. If this method returns a non-null value, then the cache will be updated to map key to that value, and that value will be returned by the get method.

The default implementation of this method simply returns null for every key value. A subclass may override this method to provide more useful behavior.

Parameters
key:Object

The key for which a value is to be computed

Returns:V

A value for key, or null if one could not be computed

See Also
get
getback to summary
public V get(Object key)

Overrides java.util.AbstractMap.get.

Implements java.util.Map.get.

Return the value to which this cache maps the specified key. If the cache does not presently contain a value for this key, then invoke the fill method in an attempt to compute such a value. If that method returns a non-null value, then update the cache and return the new value. Otherwise, return null.

Note that because this method may update the cache, it is considered a mutator and may cause ConcurrentModificationExceptions to be thrown if invoked while an iterator is in use.

Parameters
key:Object

The key whose associated value, if any, is to be returned

Annotations
@Override
@SuppressWarnings:unchecked
See Also
fill
isEmptyback to summary
public boolean isEmpty()

Overrides java.util.AbstractMap.isEmpty.

Implements java.util.Map.isEmpty.

Return true if this cache contains no key-value mappings.

Annotations
@Override
processQueueback to summary
private void processQueue()
Annotations
@SuppressWarnings:unchecked
putback to summary
public V put(K key, V value)

Overrides java.util.AbstractMap.put.

Implements java.util.Map.put.

Update this cache so that the given key maps to the given value. If the cache previously contained a mapping for key then that mapping is replaced and the old value is returned.

Parameters
key:K

The key that is to be mapped to the given value

value:V

The value to which the given key is to be mapped

Returns:V

The previous value to which this key was mapped, or null if if there was no mapping for the key

Annotations
@Override
removeback to summary
public V remove(Object key)

Overrides java.util.AbstractMap.remove.

Implements java.util.Map.remove.

Remove the mapping for the given key from this cache, if present.

Parameters
key:Object

The key whose mapping is to be removed

Returns:V

The value to which this key was mapped, or null if there was no mapping for the key

Annotations
@Override
sizeback to summary
public int size()

Overrides java.util.AbstractMap.size.

Implements java.util.Map.size.

Return the number of key-value mappings in this cache. The time required by this operation is linear in the size of the map.

Annotations
@Override
valEqualsback to summary
private static boolean valEquals(Object o1, Object o2)
org.glassfish.pfl.basic.concurrent back to summary

private Class SoftCache.Entry

extends Object
implements Map.Entry<K, V>
Class Inheritance
All Implemented Interfaces
java.util.Map.Entry

Field Summary

Modifier and TypeField and Description
private Map.Entry<K, SoftCache.ValueCell<K, V>>
private V

Constructor Summary

AccessConstructor and Description
pack-priv
Entry(Map.Entry<K, SoftCache.ValueCell<K, V>> ent, V value)

Method Summary

Modifier and TypeMethod and Description
public boolean
equals(Object o)

Overrides java.lang.Object.equals.

Implements java.util.Map.Entry.equals.

Compares the specified object with this entry for equality.

public K
getKey()

Implements java.util.Map.Entry.getKey.

Returns the key corresponding to this entry.

public V
getValue()

Implements java.util.Map.Entry.getValue.

Returns the value corresponding to this entry.

public int
hashCode()

Overrides java.lang.Object.hashCode.

Implements java.util.Map.Entry.hashCode.

Returns the hash code value for this map entry.

public V
setValue(V value)

Implements java.util.Map.Entry.setValue.

Replaces the value corresponding to this entry with the specified value (optional operation).

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAlltoStringwaitwaitwait

Field Detail

entback to summary
private Map.Entry<K, SoftCache.ValueCell<K, V>> ent
valueback to summary
private V value

Constructor Detail

Entryback to summary
pack-priv Entry(Map.Entry<K, SoftCache.ValueCell<K, V>> ent, V value)

Method Detail

equalsback to summary
public boolean equals(Object o)

Overrides java.lang.Object.equals.

Implements java.util.Map.Entry.equals.

Doc from java.util.Map.Entry.equals.

Compares the specified object with this entry for equality. Returns true if the given object is also a map entry and the two entries represent the same mapping. More formally, two entries e1 and e2 represent the same mapping if

    (e1.getKey()==null ?
     e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &&
    (e1.getValue()==null ?
     e2.getValue()==null : e1.getValue().equals(e2.getValue()))
This ensures that the equals method works properly across different implementations of the Map.Entry interface.
Annotations
@Override
getKeyback to summary
public K getKey()

Implements java.util.Map.Entry.getKey.

Doc from java.util.Map.Entry.getKey.

Returns the key corresponding to this entry.

Annotations
@Override
getValueback to summary
public V getValue()

Implements java.util.Map.Entry.getValue.

Doc from java.util.Map.Entry.getValue.

Returns the value corresponding to this entry. If the mapping has been removed from the backing map (by the iterator's remove operation), the results of this call are undefined.

Annotations
@Override
hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Implements java.util.Map.Entry.hashCode.

Doc from java.util.Map.Entry.hashCode.

Returns the hash code value for this map entry. The hash code of a map entry e is defined to be:

    (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
    (e.getValue()==null ? 0 : e.getValue().hashCode())
This ensures that e1.equals(e2) implies that e1.hashCode()==e2.hashCode() for any two Entries e1 and e2, as required by the general contract of Object.hashCode.
Annotations
@Override
setValueback to summary
public V setValue(V value)

Implements java.util.Map.Entry.setValue.

Doc from java.util.Map.Entry.setValue.

Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).

Annotations
@Override
org.glassfish.pfl.basic.concurrent back to summary

private Class SoftCache.EntrySet

extends AbstractSet<Map.Entry<K, V>>
Class Inheritance

Field Summary

Modifier and TypeField and Description
pack-priv Set<Map.Entry<K, SoftCache.ValueCell<K, V>>>

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public boolean
isEmpty()

Overrides java.util.AbstractCollection.isEmpty.

Implements java.util.Set.isEmpty, java.util.Collection.isEmpty.

Returns true if this set contains no elements.

public Iterator<Map.Entry<K, V>>
iterator()

Implements abstract java.util.AbstractCollection.iterator.

Implements java.util.Set.iterator, java.util.Collection.iterator.

Returns an iterator over the elements in this set.

public boolean
remove(Map.Entry<K, V> o)

public int
size()

Implements abstract java.util.AbstractCollection.size.

Implements java.util.Set.size, java.util.Collection.size.

Returns the number of elements in this set (its cardinality).

Inherited from java.util.AbstractSet:
equalshashCoderemoveAll

Field Detail

hashEntriesback to summary
pack-priv Set<Map.Entry<K, SoftCache.ValueCell<K, V>>> hashEntries

Constructor Detail

EntrySetback to summary
private EntrySet()

Method Detail

isEmptyback to summary
public boolean isEmpty()

Overrides java.util.AbstractCollection.isEmpty.

Implements java.util.Set.isEmpty, java.util.Collection.isEmpty.

Doc from java.util.Set.isEmpty.

Returns true if this set contains no elements.

Annotations
@Override
iteratorback to summary
public Iterator<Map.Entry<K, V>> iterator()

Implements abstract java.util.AbstractCollection.iterator.

Implements java.util.Set.iterator, java.util.Collection.iterator.

Doc from java.util.Set.iterator.

Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).

Annotations
@Override
removeback to summary
public boolean remove(Map.Entry<K, V> o)
sizeback to summary
public int size()

Implements abstract java.util.AbstractCollection.size.

Implements java.util.Set.size, java.util.Collection.size.

Doc from java.util.Set.size.

Returns the number of elements in this set (its cardinality). If this set contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Annotations
@Override
org.glassfish.pfl.basic.concurrent back to summary

private Class SoftCache.ValueCell<K, V>

extends SoftReference<V>
Class Inheritance

Field Summary

Modifier and TypeField and Description
private static int
private K
private boolean

Constructor Summary

AccessConstructor and Description
private
ValueCell(K key, V value, ReferenceQueue<V> queue)

Method Summary

Modifier and TypeMethod and Description
private static <K, V> SoftCache.ValueCell<K, V>
create(K key, V value, ReferenceQueue<V> queue)

private void
drop()

private boolean
private static <K, V> V
strip(SoftCache.ValueCell<K, V> val, boolean drop)

Inherited from java.lang.ref.SoftReference:
get

Field Detail

droppedback to summary
private static int dropped
keyback to summary
private K key
keyIsValidback to summary
private boolean keyIsValid

Constructor Detail

ValueCellback to summary
private ValueCell(K key, V value, ReferenceQueue<V> queue)

Method Detail

createback to summary
private static <K, V> SoftCache.ValueCell<K, V> create(K key, V value, ReferenceQueue<V> queue)
Annotations
@SuppressWarnings:unchecked
dropback to summary
private void drop()
isValidback to summary
private boolean isValid()
stripback to summary
private static <K, V> V strip(SoftCache.ValueCell<K, V> val, boolean drop)