Middle
Do you know how a cache card works?
sobes.tech AI
Answer from AI
Memory Cache in Android is a mechanism for storing data in the device's RAM for quick access. It is based on the principles of associative cache.
How it works:
- Data request: When data that can be cached is requested (e.g., an image from the network or the result of a complex operation), the app first checks the cache.
- Cache lookup: If data is found in the cache (i.e., the request key matches a key in the cache), it is returned immediately, avoiding slow I/O operations or computations. This is called a "cache hit".
- Cache miss: If data is not found in the cache, the app retrieves it from the original source (network, database, etc.).
- Caching: The retrieved data is then stored in the cache for future requests with the same key.
- Eviction: The cache has a limited size. When it fills up, old or less-used entries are evicted to make room for new data. Common eviction algorithms include LRU (Least Recently Used) and LFU (Least Frequently Used).
Example implementation in Android using LruCache:
// Creating an LruCache with a maximum size
private LruCache<String, Bitmap> memoryCache;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the maximum available memory for the app (in KB)
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8 of the available memory for cache
final int cacheSize = maxMemory / 8;
memoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// Method to calculate the size of each cache item in units (here - KB)
return bitmap.getByteCount() / 1024;
}
};
}
// Add an item to cache
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
memoryCache.put(key, bitmap);
}
}
// Retrieve an item from cache
public Bitmap getBitmapFromMemCache(String key) {
return memoryCache.get(key);
}