Class UnifiedCacheBase<K,V>
- java.lang.Object
-
- io.github.dhruv1110.jcachex.impl.base.UnifiedCacheBase<K,V>
-
- Type Parameters:
K
- the type of keys maintained by this cacheV
- the type of mapped values
- All Implemented Interfaces:
Cache<K,V>
public abstract class UnifiedCacheBase<K,V> extends Object implements Cache<K,V>
Unified base class for all cache implementations providing comprehensive functionality.This class consolidates functionality from multiple inheritance layers into a single, efficient base class that provides:
- Core Operations: Parameter validation, statistics tracking, configuration management
- Data Storage: ConcurrentHashMap-based storage with optimal capacity calculation
- Concurrency: Striped locking, thread-safe operations, eviction management
- Collection Views: Efficient keys(), values(), entries() implementations
- Async Operations: CompletableFuture-based async method implementations
- Event Handling: Event listener notification system
- Maintenance: Scheduled cleanup and expiration handling
This unified approach eliminates the complexity of multiple inheritance layers while providing all necessary functionality for cache implementations.
- Since:
- 1.0.0
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static class
UnifiedCacheBase.ImmutableMapEntry<K,V>
Immutable map entry for collection views.
-
Field Summary
Fields Modifier and Type Field Description protected CacheConfig<K,V>
config
protected AtomicLong
currentSize
protected AtomicLong
currentWeight
protected ConcurrentHashMap<K,CacheEntry<V>>
data
protected CacheEventListener<K,V>
eventListener
protected EvictionStrategy<K,V>
evictionStrategy
protected boolean
hasExpiration
protected boolean
hasMaximumSize
protected boolean
hasMaximumWeight
protected AtomicLong
hitCount
protected long
maximumSize
protected AtomicLong
missCount
protected ScheduledExecutorService
scheduler
protected CacheStats
stats
protected boolean
statsEnabled
protected static int
STRIPE_COUNT
protected ReentrantReadWriteLock[]
stripes
-
Constructor Summary
Constructors Modifier Constructor Description protected
UnifiedCacheBase(CacheConfig<K,V> config)
Constructor for all cache implementations.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description protected static int
calculateOptimalCapacity(long maximumSize)
Calculates optimal capacity for the underlying ConcurrentHashMap.protected void
cleanupExpiredEntries()
Cleans up expired entries.void
clear()
Removes all mappings from this cache.CompletableFuture<Void>
clearAsync()
Asynchronously removes all mappings from this cache.CacheConfig<K,V>
config()
Returns the cache configuration.boolean
containsKey(K key)
Returns true if this cache contains a mapping for the specified key.protected abstract void
doClear()
Implementation-specific clear operation.protected abstract boolean
doContainsKey(K key)
Implementation-specific containsKey operation.protected abstract V
doGet(K key)
Implementation-specific get operation.protected abstract void
doPut(K key, V value)
Implementation-specific put operation.protected abstract V
doRemove(K key)
Implementation-specific remove operation.Set<Map.Entry<K,V>>
entries()
Returns a view of all the key-value pairs in this cache.V
get(K key)
Returns the value associated with the key in this cache, or null if there is no cached value for the key.CompletableFuture<V>
getAsync(K key)
Asynchronously returns the value associated with the key in this cache.protected int
getStripeIndex(K key)
Gets the stripe index for a key.protected boolean
isSizeLimitReached()
Checks if size limit has been reached.protected boolean
isValidEntry(CacheEntry<V> entry)
Checks if an entry is valid (not expired, etc.).Set<K>
keys()
Returns a view of all the keys in this cache.void
put(K key, V value)
Associates the specified value with the specified key in this cache.CompletableFuture<Void>
putAsync(K key, V value)
Asynchronously associates the specified value with the specified key in this cache.protected void
recordClearStatistics(long sizeBefore)
Records statistics for clear operations.protected void
recordGetStatistics(boolean hit)
Records statistics for get operations.protected void
recordPutStatistics()
Records statistics for put operations.protected void
recordRemoveStatistics(boolean removed)
Records statistics for remove operations.protected void
refreshStaleEntries()
Refreshes stale entries.V
remove(K key)
Removes the mapping for a key from this cache if it is present.CompletableFuture<V>
removeAsync(K key)
Asynchronously removes the mapping for a key from this cache if it is present.protected void
scheduleCleanup()
Schedules cleanup operations for expired entries.protected void
scheduleRefresh()
Schedules refresh operations.void
shutdown()
Shuts down the cache and cleans up resources.long
size()
Returns the approximate number of entries in this cache.CacheStats
stats()
Returns the cache statistics.protected void
triggerEviction()
Triggers eviction when size limit is reached.protected void
updateStatsFromCounters()
Updates statistics from internal counters.protected boolean
validateKey(K key)
Validates that a key is not null.protected boolean
validateValue(V value)
Validates that a value is acceptable.Collection<V>
values()
Returns a view of all the values in this cache.
-
-
-
Field Detail
-
config
protected final CacheConfig<K,V> config
-
stats
protected final CacheStats stats
-
statsEnabled
protected final boolean statsEnabled
-
maximumSize
protected final long maximumSize
-
hasExpiration
protected final boolean hasExpiration
-
hasMaximumSize
protected final boolean hasMaximumSize
-
hasMaximumWeight
protected final boolean hasMaximumWeight
-
data
protected final ConcurrentHashMap<K,CacheEntry<V>> data
-
hitCount
protected final AtomicLong hitCount
-
missCount
protected final AtomicLong missCount
-
currentSize
protected final AtomicLong currentSize
-
currentWeight
protected final AtomicLong currentWeight
-
STRIPE_COUNT
protected static final int STRIPE_COUNT
- See Also:
- Constant Field Values
-
stripes
protected final ReentrantReadWriteLock[] stripes
-
evictionStrategy
protected final EvictionStrategy<K,V> evictionStrategy
-
eventListener
protected final CacheEventListener<K,V> eventListener
-
scheduler
protected final ScheduledExecutorService scheduler
-
-
Constructor Detail
-
UnifiedCacheBase
protected UnifiedCacheBase(CacheConfig<K,V> config)
Constructor for all cache implementations.- Parameters:
config
- the cache configuration- Throws:
IllegalArgumentException
- if config is null
-
-
Method Detail
-
get
public final V get(K key)
Description copied from interface:Cache
Returns the value associated with the key in this cache, or null if there is no cached value for the key.
-
put
public final void put(K key, V value)
Description copied from interface:Cache
Associates the specified value with the specified key in this cache.
-
remove
public final V remove(K key)
Description copied from interface:Cache
Removes the mapping for a key from this cache if it is present.
-
clear
public final void clear()
Description copied from interface:Cache
Removes all mappings from this cache.
-
containsKey
public final boolean containsKey(K key)
Description copied from interface:Cache
Returns true if this cache contains a mapping for the specified key.- Specified by:
containsKey
in interfaceCache<K,V>
- Parameters:
key
- key whose presence in this cache is to be tested- Returns:
- true if this cache contains a mapping for the specified key
-
size
public final long size()
Description copied from interface:Cache
Returns the approximate number of entries in this cache.
-
keys
public final Set<K> keys()
Description copied from interface:Cache
Returns a view of all the keys in this cache.
-
values
public final Collection<V> values()
Description copied from interface:Cache
Returns a view of all the values in this cache.
-
entries
public final Set<Map.Entry<K,V>> entries()
Description copied from interface:Cache
Returns a view of all the key-value pairs in this cache.
-
getAsync
public CompletableFuture<V> getAsync(K key)
Description copied from interface:Cache
Asynchronously returns the value associated with the key in this cache.
-
putAsync
public CompletableFuture<Void> putAsync(K key, V value)
Description copied from interface:Cache
Asynchronously associates the specified value with the specified key in this cache.
-
removeAsync
public CompletableFuture<V> removeAsync(K key)
Description copied from interface:Cache
Asynchronously removes the mapping for a key from this cache if it is present.- Specified by:
removeAsync
in interfaceCache<K,V>
- Parameters:
key
- key whose mapping is to be removed from the cache- Returns:
- a CompletableFuture that will be completed with the previous value associated with key, or null if there was no mapping for key
-
clearAsync
public CompletableFuture<Void> clearAsync()
Description copied from interface:Cache
Asynchronously removes all mappings from this cache.- Specified by:
clearAsync
in interfaceCache<K,V>
- Returns:
- a CompletableFuture that will be completed when the operation is done
-
config
public final CacheConfig<K,V> config()
Description copied from interface:Cache
Returns the cache configuration.
-
stats
public final CacheStats stats()
Description copied from interface:Cache
Returns the cache statistics.
-
doGet
protected abstract V doGet(K key)
Implementation-specific get operation.- Parameters:
key
- the key (already validated)- Returns:
- the value or null if not found/expired
-
doPut
protected abstract void doPut(K key, V value)
Implementation-specific put operation.- Parameters:
key
- the key (already validated)value
- the value (already validated)
-
doRemove
protected abstract V doRemove(K key)
Implementation-specific remove operation.- Parameters:
key
- the key (already validated)- Returns:
- the removed value or null if not found
-
doClear
protected abstract void doClear()
Implementation-specific clear operation.
-
doContainsKey
protected abstract boolean doContainsKey(K key)
Implementation-specific containsKey operation.- Parameters:
key
- the key (already validated)- Returns:
- true if key exists and is not expired
-
validateKey
protected boolean validateKey(K key)
Validates that a key is not null.
-
validateValue
protected boolean validateValue(V value)
Validates that a value is acceptable.
-
isValidEntry
protected boolean isValidEntry(CacheEntry<V> entry)
Checks if an entry is valid (not expired, etc.).
-
recordGetStatistics
protected void recordGetStatistics(boolean hit)
Records statistics for get operations.
-
recordPutStatistics
protected void recordPutStatistics()
Records statistics for put operations.
-
recordRemoveStatistics
protected void recordRemoveStatistics(boolean removed)
Records statistics for remove operations.
-
recordClearStatistics
protected void recordClearStatistics(long sizeBefore)
Records statistics for clear operations.
-
updateStatsFromCounters
protected void updateStatsFromCounters()
Updates statistics from internal counters.
-
isSizeLimitReached
protected boolean isSizeLimitReached()
Checks if size limit has been reached.
-
triggerEviction
protected void triggerEviction()
Triggers eviction when size limit is reached.
-
calculateOptimalCapacity
protected static int calculateOptimalCapacity(long maximumSize)
Calculates optimal capacity for the underlying ConcurrentHashMap.
-
getStripeIndex
protected int getStripeIndex(K key)
Gets the stripe index for a key.
-
scheduleCleanup
protected void scheduleCleanup()
Schedules cleanup operations for expired entries.
-
scheduleRefresh
protected void scheduleRefresh()
Schedules refresh operations.
-
cleanupExpiredEntries
protected void cleanupExpiredEntries()
Cleans up expired entries.
-
refreshStaleEntries
protected void refreshStaleEntries()
Refreshes stale entries.
-
shutdown
public void shutdown()
Shuts down the cache and cleans up resources.
-
-