Class WeakCache<K,V>
java.lang.Object
org.glassfish.pfl.basic.concurrent.WeakCache<K,V>
A simple cache with weak keys. get may be called safely with good
concurrency by multiple threads. In order to use this, some reasonable
properties are expected:
- The value is a function of only the key, so it may be safely cached.
- get operations are very common on the same key.
- Values may occasionally disappear from the cache, in which case they will just be recomputed on the next get() call.
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
-
Field Details
-
lock
-
map
-
-
Constructor Details
-
WeakCache
public WeakCache()
-
-
Method Details
-
lookup
Must be implemented in a subclass. Must compute a value corresponding to a key. The computation may be fairly expensive. Note that no lock is held during this computation.- Parameters:
key
- Key value for which a value must be computed.- Returns:
- The resulting value.
-
remove
Remove any value associated with the key.- Parameters:
key
- Key to value that may be in cache.- Returns:
- value from the cache, or null if none.
-
get
Return the value (if any) associated with key. If the value is already in the cache, only a read lock is held, so many threads can concurrently call get. If no value is in the cache corresponding to key, a new value will be computed and cached, in which case a write lock is held long enough to update the map. Note that the write lock is NOT held while the value is computed by calling the lookup method. Because of this, it is possible for redundant computation to occur when two or more thread concurrently call get on the same key which is not (yet) in the cache.- Parameters:
key
-- Returns:
- Value associated with the key.
-
clear
public void clear()Remove all entries from the cache.
-