How can cache functionality be implemented in Java?

In Java, caching functionality can be implemented using HashMap or LinkedHashMap.

To begin with, define a Cache class for storing cache data and providing corresponding methods.

import java.util.HashMap;
import java.util.Map;

public class Cache<K, V> {
    private Map<K, V> cacheMap;
    private int maxSize;

    public Cache(int maxSize) {
        this.maxSize = maxSize;
        this.cacheMap = new LinkedHashMap<K, V>() {
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > Cache.this.maxSize;
            }
        };
    }

    public synchronized V get(K key) {
        return cacheMap.get(key);
    }

    public synchronized void put(K key, V value) {
        cacheMap.put(key, value);
    }

    public synchronized void remove(K key) {
        cacheMap.remove(key);
    }

    public synchronized void clear() {
        cacheMap.clear();
    }

    public synchronized int size() {
        return cacheMap.size();
    }
}

In the above code, a LinkedHashMap is used as the underlying data structure and a fixed maximum capacity maxSize is set. When the cache’s data exceeds the maximum capacity, the oldest data will be automatically deleted.

Later, the Cache class can be used in places where caching is needed. For example, if there is a method that needs to read data from a database, caching can be used to improve performance.

public class Database {
    private Cache<String, String> cache;

    public Database() {
        // 创建一个大小为100的缓存
        this.cache = new Cache<>(100);
    }

    public String getData(String key) {
        // 先尝试从缓存中获取数据
        String data = cache.get(key);
        if (data == null) {
            // 如果缓存中没有,则从数据库中获取数据
            data = fetchDataFromDatabase(key);
            // 将数据放入缓存
            cache.put(key, data);
        }
        return data;
    }

    private String fetchDataFromDatabase(String key) {
        // 从数据库中获取数据
        // ...
        return data;
    }
}

In the above code, first attempt to retrieve data from the cache. If the data is not found in the cache, then retrieve it from the database and store it in the cache.

By utilizing caching, the number of database accesses can be reduced, increasing program performance. Additionally, caching can also be used for other scenarios that require frequent reading and writing, like network requests and computation results.

bannerAds