Class MemoryCache
-
- All Implemented Interfaces:
-
com.sap.cloud.mobile.foundation.cache.Cache
,com.sap.cloud.mobile.foundation.cache.CacheBuilder
public final class MemoryCache<K, V> extends CacheBase<K, V> implements CacheBuilder<K, V>
MemoryCache is a fixed size in-memory cache that uses weak reference keys to store a set of values with the following features and options:
- LRU (Least Recently Used) Cache Replacement Policy: Each time a value is accessed, it is moved to the end of a queue in descending LRU order. When an entry is added to a full cache, the entry at the head of that queue, that is, the Least Recently Used entry is evicted to make room for the new entry.
- Clear on Memory Error Option: When this option is turned on, low memory situation detected by the application will cause the entire cache to be cleared.
Cost Factor Option: The cache can be configured with a maximum cost, and a cost provided by the user is associated with each cache entry during the put operation.
In addition to the LRU Replacement Policy, when the aggregated cost exceeds the maximum cost, one or more cache entries based on system or user-defined eviction criteria will be removed to make space for the current entry, then adds the current entry to the cache:
- System Eviction Criteria-- the current entry with the highest cost will be removed.
- Customized Eviction Criteria-- a list of existing entries sorted in ascending cost order will be presented to the user via a callback interface CacheCostFactor, the user-defined callback method
List<K> onExceedMaxCost(final List<K> existingKeys)
can select and return a list of one or more entries from the input list to evict.
Before interacting with the
MemoryCache
, you need to instantiate and configure theMemoryCache
. Any operation performed before the cache is properly configured will incur an error.int maxSize = 32; // Specifies the key and value type, Android application context and maximum size. MemoryCache<String, Employee> cache = new MemoryCache<>(androidContext, maxSize);
- With no options
- Clear On Memory Error option-- Enables the 'Clear On Memory Error' option. The user also needs to invoke onLowMemory in Android onLowMemory life cycle method.
- Cost Factor option with the default system eviction criteria-- The user can enable and specify the maximum total cost, and uses system eviction criteria by not calling addCostFactor.
- Cost Factor option with custom eviction criteria-- In addition to the maximum total cost, the user can provide custom eviction criteria via CacheCostFactor interface.
-
-
Field Summary
Fields Modifier and Type Field Description public double
maximumCost
public final static int
DEFAULT_MAX_ENTRIES
public Context
context
public int
maxEntries
-
Constructor Summary
Constructors Constructor Description MemoryCache(Context context, int maxEntries)
Instantiates a Memory Cache instance.
-
Method Summary
Modifier and Type Method Description synchronized double
getMaximumCost()
Returns the maximum cost allowed when Cost Factor is enabled. synchronized MemoryCache<K, V>
build()
Completes the Memory Cache instance configuration. MemoryCache<K, V>
maxCost(double maxCost)
Enables the Cost Factor mechanism by providing the maximum cost allowed. <T extends CacheCostFactor<K>> MemoryCache<K, V>
addCostFactor(@NonNull() T costFactor)
Assuming Cost Factor mechanism has been enabled via maxCost, this method provides customized cache replacement method maxCostExceeded when the aggregated cost exceeds the maximum cost during put. void
onLowMemory()
When the system is running low on memory, evicts all entries in the cache if clearOnMemoryError was called during Memory Cache initialization. MemoryCache<K, V>
clearOnMemoryError()
Sets a flag so that when low memory condition occurs, all cache entries will be removed(clearing the cache). synchronized double
getCostOfEntries()
Returns the aggregated value of the costs for the cache entries added so far when Cost Factor option is enabled (via addCostFactor. int
getEntryCount()
Returns the number of entries (key-value pairs) in the cache. V
put(@NonNull() K key, @NonNull() V value, double cost)
Adds the value and the associated cost to the cache for the key. V
put(@NonNull() K key, @NonNull() V value)
Adds the value in the cache with the given key. V
get(@NonNull() K key)
Returns the value associated with a key. CacheEntry<K, V>
getEntry(@NonNull() K key)
Retrieves the value associated with a key, then returns a CacheEntry
object that embeds the key and value.List<K>
keys()
Returns a list of keys of existing entries. void
remove(@NonNull() K key)
Removes a cache entry. void
removeAll()
Removes all entries from the cache. -
-
Method Detail
-
getMaximumCost
synchronized double getMaximumCost()
Returns the maximum cost allowed when Cost Factor is enabled.
- Returns:
The maximum cost allowed, set via addCostFactor before build.
-
build
@NonNull() synchronized MemoryCache<K, V> build()
Completes the Memory Cache instance configuration. The cache CRUD operations are only then enabled after returning from this call.
1. The cache size have the maximum entries specified via MemoryCache.
2. The cache will evict all cache entries if clearOnMemoryError has been called.
3. When Cost Factor mechanism is enabled:
a. No customized onExceedMaxCost is provided (via addCostFactor), a system default method will be invoked to remove the most costly entry amongst the existing entries during a call to put, then proceeds with the original put operation. b. Otherwise, the customized onExceedMaxCost will be invoked to remove the selected entry/entries before proceeding with the put operation.
- Returns:
this
instance of Memory Cache.
-
maxCost
@NonNull() MemoryCache<K, V> maxCost(double maxCost)
Enables the Cost Factor mechanism by providing the maximum cost allowed.
Note that the user must calls this method before providing the optional customized CacheCostFactor.
When the Cost Factor mechanism is enabled and if a customized CacheCostFactor is not specified, a default onExceedMaxCost method will be used, which will will provide the most costly cache entry to remove when a the aggregated costs during put exceeds the maximum costs.
- Parameters:
maxCost
- Adouble
number > 0.- Returns:
this
instance of memory cache.
-
addCostFactor
@NonNull() <T extends CacheCostFactor<K>> MemoryCache<K, V> addCostFactor(@NonNull() T costFactor)
Assuming Cost Factor mechanism has been enabled via maxCost, this method provides customized cache replacement method maxCostExceeded when the aggregated cost exceeds the maximum cost during put.
- Parameters:
costFactor
- An instance of CacheCostFactor- Returns:
this
Memory Cache that can call build to finalize the memory cache configuration.
-
onLowMemory
void onLowMemory()
When the system is running low on memory, evicts all entries in the cache if clearOnMemoryError was called during Memory Cache initialization.
This method should be called from Android component's onLowMemory or onTrimMemory, and the system will perform a garbage collection after returning from that method.
-
clearOnMemoryError
@NonNull() MemoryCache<K, V> clearOnMemoryError()
Sets a flag so that when low memory condition occurs, all cache entries will be removed(clearing the cache).
The clear on low memory action is taken when:
1. The application component implemented onLowMemory or onLowMemory, and called onLowMemory.
2. OutOfMemoryError is detected inside Memory Cache, and onLowMemory will be invoked internally.
- Returns:
The same cache instance this method was called upon.
-
getCostOfEntries
synchronized double getCostOfEntries()
Returns the aggregated value of the costs for the cache entries added so far when Cost Factor option is enabled (via addCostFactor.
- Returns:
The aggregated value of the costs, or 0 if Cost Factor option is not enabled.
-
getEntryCount
int getEntryCount()
Returns the number of entries (key-value pairs) in the cache.
- Returns:
The number of entries.
-
put
@Nullable() V put(@NonNull() K key, @NonNull() V value, double cost)
Adds the value and the associated cost to the cache for the key. Only valid if maxCost was called.
- Parameters:
key
-non-null
key of the cache entryvalue
-non-null
value of the cache entrycost
- a cost > 0 associated with this entry- Returns:
The previous value associated with the existed
key
,null
otherwise.
-
put
@Nullable() V put(@NonNull() K key, @NonNull() V value)
Adds the value in the cache with the given key.
- Parameters:
key
-non-null
key of the cache entryvalue
-non-null
value of the cache entry- Returns:
The previous value associated with the existed
key
,null
otherwise.
-
get
@Nullable() V get(@NonNull() K key)
Returns the value associated with a key.
- Parameters:
key
- anon-null
key of a cache entry- Returns:
The value associated with a key or
null
if the key is not found.
-
getEntry
@Nullable() CacheEntry<K, V> getEntry(@NonNull() K key)
Retrieves the value associated with a key, then returns a
CacheEntry
object that embeds the key and value.- Parameters:
key
- anon-null
key of a cache entry- Returns:
A CacheEntry or
null
if the key is not found.
-
keys
@NonNull() List<K> keys()
Returns a list of keys of existing entries.
- Returns:
An non-
null
list that is empty or contains keys in LRU descending order, that is, the first entry in the list is the least recently used.
-
remove
void remove(@NonNull() K key)
Removes a cache entry.
- Parameters:
key
- anon-null
key of the entry to remove
-
removeAll
void removeAll()
Removes all entries from the cache.
-
-
-
-