Class SoftReferenceCache
- All Implemented Interfaces:
Cache, AutoCloseable
Cache implementation using key-level synchronized access and soft references for value storage.
This cache is optimized for concurrent environments and provides built-in support for:
- Automatic eviction based on max size (LRU policy)
- Reference-based eviction when values are no longer strongly reachable (via
SoftReference) - Expiration after a configurable duration
- Eviction notification via registered
CacheEvictionlisteners
The cache ensures thread safety through synchronized access on its internal LinkedHashMap and striped locking
for computations. Equal keys always use the same stripe, preserving atomic updates without allocating or globally
interning a lock value for every cache operation.
Threading: Eviction listeners and expiration polling run on background threads.
The valueMap itself is backed by a synchronized LinkedHashMap with LRU eviction behavior.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static interfaceclassprotected class -
Constructor Summary
ConstructorsModifierConstructorDescriptionConstructs a cache with a default maximum size of 1,000,000 entries and no expiration.SoftReferenceCache(int maxSize) Constructs a cache with a specified max size and no expiration.SoftReferenceCache(int maxSize, Duration expiry) Constructs a cache with specified size and expiration.SoftReferenceCache(int maxSize, Executor evictionNotifier, Duration expiry) Constructs a cache with specified size, executor for eviction notifications and expiration.SoftReferenceCache(int maxSize, Executor evictionNotifier, Duration expiry, Duration expiryCheckDelay, boolean softReferences) Constructs a cache with full configuration of size, eviction executor, expiration delay, and expiration check frequency.protectedSoftReferenceCache(int maxSize, Executor evictionNotifier, Duration expiry, Duration expiryCheckDelay, boolean softReferences, Clock clock) -
Method Summary
Modifier and TypeMethodDescriptionvoidclear()Removes all entries from the cache.voidclose()Closes the cache and releases all associated resources.<T> Tcompute(Object id, BiFunction<? super Object, ? super T, ? extends T> mappingFunction) Returns a synchronized computation that adds, removes, or updates a cache entry.<T> TcomputeIfAbsent(Object id, Function<? super Object, T> mappingFunction) If a value is not already associated with the givenid, computes and stores one using the given function.<T> TcomputeIfPresent(Object id, BiFunction<? super Object, ? super T, ? extends T> mappingFunction) If a value is already associated with the givenid, computes a new value using the provided function and replaces the old one.booleancontainsKey(Object id) Checks whether the cache contains an entry for the givenid.<T> TRetrieves the value associated with the givenid, ornullif not found.<T> voidmergeAll(Map<?, ? extends T> values, BiFunction<? super T, ? super T, ? extends T> mergeFunction) Merges a bounded group of candidate values into this cache.<T> voidmodifyEach(BiFunction<? super Object, ? super T, ? extends T> modifierFunction) Applies the given modifier function to all values currently in the cache.protected voidPuts a value in the cache for the givenid, overwriting any existing value.putIfAbsent(Object id, Object value) Associates the specified value with the givenidonly if no value is currently associated.rebuild()Returns a fresh cache instance with the same configuration and no stored entries.protected voidregisterEviction(SoftReferenceCache.CacheReference reference, CacheEviction.Reason reason) registerEvictionListener(Consumer<CacheEviction> listener) Registers a listener to be notified whenever a cache entry is evicted or removed.<T> TRemoves the entry associated with the givenid, if present.protected voidintsize()Returns the number of entries currently stored in the cache.protected <T> T<T> voidApplies independent per-key update functions as one bounded cache operation.protected SoftReferenceCache.CacheReference
-
Constructor Details
-
SoftReferenceCache
public SoftReferenceCache()Constructs a cache with a default maximum size of 1,000,000 entries and no expiration. -
SoftReferenceCache
public SoftReferenceCache(int maxSize) Constructs a cache with a specified max size and no expiration. -
SoftReferenceCache
Constructs a cache with specified size and expiration. Uses a single-threaded executor for eviction notifications. -
SoftReferenceCache
-
SoftReferenceCache
-
SoftReferenceCache
-
-
Method Details
-
compute
Returns a synchronized computation that adds, removes, or updates a cache entry. A fixed hash stripe preserves per-key atomicity without allocating and globally interning a mutex String for every cache operation. -
mergeAll
public <T> void mergeAll(Map<?, ? extends T> values, BiFunction<? super T, ? super T, ? extends T> mergeFunction) Description copied from interface:CacheMerges a bounded group of candidate values into this cache.The default implementation preserves the ordinary per-key
Cache.compute(Object, BiFunction)contract. Implementations may override this method to reduce lock transitions while retaining the same per-key merge semantics. The group as a whole is not an atomic transaction. -
updateAll
Description copied from interface:CacheApplies independent per-key update functions as one bounded cache operation.The default implementation preserves the ordinary per-key
Cache.compute(Object, BiFunction)contract. Implementations may override this method to amortize shared bookkeeping or lock transitions. The group as a whole is not an atomic transaction. -
modifyEach
Description copied from interface:CacheApplies the given modifier function to all values currently in the cache.This is useful for bulk modifications, e.g. adjusting internal state after a system-wide change.
- Specified by:
modifyEachin interfaceCache- Type Parameters:
T- the expected type of the values- Parameters:
modifierFunction- the function to apply to each entry
-
put
Description copied from interface:CachePuts a value in the cache for the givenid, overwriting any existing value. -
putIfAbsent
Description copied from interface:CacheAssociates the specified value with the givenidonly if no value is currently associated.- Specified by:
putIfAbsentin interfaceCache- Parameters:
id- the key to check for presencevalue- the value to associate if absent- Returns:
- the existing value associated with the key, or
nullif the new value was successfully put
-
computeIfAbsent
Description copied from interface:CacheIf a value is not already associated with the givenid, computes and stores one using the given function.- Specified by:
computeIfAbsentin interfaceCache- Type Parameters:
T- the expected type of the value- Parameters:
id- the key to check or computemappingFunction- the function to compute a value if absent- Returns:
- the current or newly computed value
-
computeIfPresent
public <T> T computeIfPresent(Object id, BiFunction<? super Object, ? super T, ? extends T> mappingFunction) Description copied from interface:CacheIf a value is already associated with the givenid, computes a new value using the provided function and replaces the old one.- Specified by:
computeIfPresentin interfaceCache- Type Parameters:
T- the expected type of the value- Parameters:
id- the key to compute formappingFunction- the function to compute a new value from the current one- Returns:
- the newly computed value, or
nullif the mapping function returnednull
-
remove
Description copied from interface:CacheRemoves the entry associated with the givenid, if present. -
get
Description copied from interface:CacheRetrieves the value associated with the givenid, ornullif not found. -
containsKey
Description copied from interface:CacheChecks whether the cache contains an entry for the givenid.- Specified by:
containsKeyin interfaceCache- Parameters:
id- the key to check- Returns:
trueif the key exists in the cache,falseotherwise
-
clear
-
size
-
registerEvictionListener
Description copied from interface:CacheRegisters a listener to be notified whenever a cache entry is evicted or removed.- Specified by:
registerEvictionListenerin interfaceCache- Parameters:
listener- a function that consumesCacheEvictions- Returns:
- a registration that can be used to cancel the listener
-
rebuild
-
close
public void close()Description copied from interface:CacheCloses the cache and releases all associated resources.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCache
-
wrap
-
unwrap
-
pollReferenceQueue
protected void pollReferenceQueue() -
removeExpiredReferences
protected void removeExpiredReferences() -
registerEviction
protected void registerEviction(SoftReferenceCache.CacheReference reference, CacheEviction.Reason reason)
-