Sobes.tech
Junior — Middle

What is the simplest method to implement a data caching mechanism?

sobes.tech AI

Answer from AI

The simplest method of implementing data caching in Java is to use a HashMap collection to store key-value pairs in memory. When data is requested, the cache is first checked for the value; if it exists, it is returned from the cache, otherwise, the data is loaded from the source and stored in the cache.

Example:

import java.util.HashMap;

public class SimpleCache {
    private HashMap<String, String> cache = new HashMap<>();

    public String getData(String key) {
        if (cache.containsKey(key)) {
            return cache.get(key); // return from cache
        }
        String data = loadDataFromSource(key); // load data
        cache.put(key, data); // store in cache
        return data;
    }

    private String loadDataFromSource(String key) {
        // simulate data loading
        return "Data for " + key;
    }
}