Android Lrucache Source Code
Android Lrucache Source Code .If you want to know about Android Lrucache Source Code , then this article is for you. You will find a lot of information about Android Lrucache Source Code in this article. We hope you find the information useful and informative. You can find more articles on the website.

What is Android?

Android, the widely popular operating system, is the beating heart behind millions of smartphones and tablets globally. Developed by Google, Android is an open-source platform that powers a diverse range of devices, offering users an intuitive and customizable experience. With its user-friendly interface, Android provides easy access to a plethora of applications through the Google Play Store, catering to every need imaginable. From social media and gaming to productivity and entertainment, Android seamlessly integrates into our daily lives, ensuring that the world is at our fingertips. Whether you're a tech enthusiast or a casual user, Android's versatility and accessibility make it a cornerstone of modern mobile technology.


Android LruCache Source Code

LruCache is a caching mechanism in Android that allows developers to store a limited amount of data in memory. It works by storing key-value pairs and evicts the least recently used items when the cache reaches its maximum size. The primary goal of LruCache is to ensure that frequently accessed data remains in memory while older or less used data is removed to make room for new data.

The LruCache class is part of the Android framework and is implemented in android.util.LruCache. Below is a breakdown of the source code for LruCache, followed by a simple implementation example.


1. The Source Code of LruCache

The LruCache class is implemented in the android.util package. Below is a simplified explanation of how it works, with its most important methods:

package android.util;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * A cache that evicts the least recently used (LRU) entries when the size limit is exceeded.
 * The cache is implemented as a subclass of LinkedHashMap and has methods for adding,
 * retrieving, and removing entries based on their recency of use.
 */
public class LruCache<K, V> {
    private final LinkedHashMap<K, V> map;
    private final int maxSize;
    private int size;

    /**
     * Constructor to initialize the cache with a specified maximum size.
     * @param maxSize The maximum size of the cache.
     */
    public LruCache(int maxSize) {
        this.maxSize = maxSize;
        this.map = new LinkedHashMap<>(16, 0.75f, true);
        this.size = 0;
    }

    /**
     * Retrieves an entry from the cache.
     * @param key The key to look up.
     * @return The value associated with the key or null if not found.
     */
    public V get(K key) {
        return map.get(key);
    }

    /**
     * Adds an entry to the cache. If the cache exceeds the max size, it evicts the least recently used entry.
     * @param key The key for the cache entry.
     * @param value The value associated with the key.
     */
    public void put(K key, V value) {
        // Check if the entry already exists, remove it if present
        if (map.containsKey(key)) {
            size -= sizeOf(key, value);
        }

        // Add the new entry
        map.put(key, value);
        size += sizeOf(key, value);

        // Evict the least recently used items if the cache exceeds its max size
        if (size > maxSize) {
            evict();
        }
    }

    /**
     * Evicts the least recently used (LRU) entry from the cache.
     */
    private void evict() {
        // Find the least recently used entry and remove it
        Map.Entry<K, V> eldest = map.entrySet().iterator().next();
        K key = eldest.getKey();
        V value = eldest.getValue();
        size -= sizeOf(key, value);
        map.remove(key);
    }

    /**
     * Gets the size of a cache entry. You can override this method if you want custom logic
     * to calculate the size of each item in the cache.
     * @param key The key for the entry.
     * @param value The value of the entry.
     * @return The size of the cache entry.
     */
    protected int sizeOf(K key, V value) {
        // By default, the size of each entry is 1, you can override this for custom sizes.
        return 1;
    }

    /**
     * Clears the cache.
     */
    public void evictAll() {
        map.clear();
        size = 0;
    }

    /**
     * Returns the current size of the cache.
     * @return The current size of the cache.
     */
    public int size() {
        return size;
    }
}

Explanation of the Code:

  1. Constructor:

    • The constructor accepts maxSize to limit the number of entries in the cache. The cache is backed by a LinkedHashMap, which allows entries to be ordered by their access order.
  2. get():

    • Retrieves a cached entry based on the key. It returns null if the entry does not exist.
  3. put():

    • Adds a new entry to the cache. It checks whether the key already exists; if it does, the old entry is removed, and the new entry is added.
    • After adding the new entry, the cache checks whether the total size exceeds maxSize. If so, the evict() method is called to remove the least recently used item.
  4. evict():

    • Removes the oldest or least recently used entry from the cache. This is done by accessing the first element in the LinkedHashMap, as it stores entries in the order of their access.
  5. sizeOf():

    • Returns the size of each entry. By default, it returns 1, assuming that each entry has the same size. This can be overridden for more complex caching mechanisms where the size of entries varies.
  6. evictAll():

    • Clears all entries in the cache.
  7. size():

    • Returns the current size of the cache in terms of entries.

2. Practical Example of Using LruCache

Let’s now look at a practical example of how you would use LruCache to store and retrieve data in an Android app. In this case, we will use an LruCache to cache images.

Example: Caching Images with LruCache

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;

public class ImageCache {
    private LruCache<String, Bitmap> mMemoryCache;

    public ImageCache() {
        // Set the cache size to 4MB
        final int cacheSize = 4 * 1024 * 1024; // 4MB
        mMemoryCache = new LruCache<>(cacheSize);
    }

    // Add Bitmap to the cache
    public void addBitmapToCache(String key, Bitmap bitmap) {
        if (getBitmapFromCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    // Get Bitmap from the cache
    public Bitmap getBitmapFromCache(String key) {
        return mMemoryCache.get(key);
    }

    // Remove Bitmap from the cache
    public void removeBitmapFromCache(String key) {
        mMemoryCache.remove(key);
    }

    // Clear all the cache entries
    public void clearCache() {
        mMemoryCache.evictAll();
    }

    // Example of loading an image
    public Bitmap loadImage(String imagePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        addBitmapToCache(imagePath, bitmap);
        return bitmap;
    }
}

Usage of ImageCache:

// Example usage in an Activity or Fragment
ImageCache imageCache = new ImageCache();

// Adding an image to the cache
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_image);
imageCache.addBitmapToCache("sample_image", bitmap);

// Retrieving the image from the cache
Bitmap cachedBitmap = imageCache.getBitmapFromCache("sample_image");

// If the bitmap is null, load it from the resources
if (cachedBitmap == null) {
    cachedBitmap = imageCache.loadImage("sample_image_path");
}

Conclusion

The LruCache class is a simple yet powerful tool for managing memory efficiently in Android applications. By storing frequently accessed data in memory and automatically evicting the least recently used items when the cache size exceeds the limit, LruCache helps optimize the use of memory and can improve the performance of your app, especially when dealing with resources like images, files, or other data that can be computationally expensive to load.

The source code provided shows the essential methods you need to work with LruCache, and the example demonstrates how to integrate it with image caching.