Sobes.tech
Senior

How to implement a local cache with thread-safe write for a specific key?

sobes.tech AI

Answer from AI

To implement a local cache with thread-safe write access for a specific key in Java, you can use the ConcurrentHashMap class. It provides high performance under concurrent access and allows safe updates of values by keys.

Example of a thread-safe cache implementation:

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class LocalCache<K, V> {
    private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>();

    // Get value from cache or compute and store if absent
    public V getOrCompute(K key, Function<K, V> mappingFunction) {
        return cache.computeIfAbsent(key, mappingFunction);
    }

    // Explicitly put a value by key
    public void put(K key, V value) {
        cache.put(key, value);
    }

    // Get value without computing
    public V get(K key) {
        return cache.get(key);
    }
}

The computeIfAbsent method guarantees that the computation and storage of a value for a specific key will occur atomically and only once, even under concurrent access from multiple threads.

If more complex update logic is needed, you can use cache.compute(key, remappingFunction), which is also thread-safe.