How to implement caching of reference books from a database in a Java application considering multithreading?
sobes.tech AI
Answer from AI
To cache reference data from a database in a Java application considering multithreading, the following approaches can be used:
-
Using thread-safe collections — for example,
ConcurrentHashMapfor cache storage. -
Initializing the cache at application startup or lazy loading using double-checked locking to avoid simultaneous data loading by multiple threads.
-
Updating the cache can be implemented through periodic reloads (for example, using
ScheduledExecutorService) or based on events. -
Using ready-made cache libraries — such as Caffeine or Guava Cache, which already provide thread safety and convenient update mechanisms.
An example of a simple cache with ConcurrentHashMap and lazy loading:
import java.util.concurrent.*;
public class ReferenceCache {
private final ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();
public String getValue(String key) {
return cache.computeIfAbsent(key, k -> loadFromDb(k));
}
private String loadFromDb(String key) {
// Simulate loading from DB
return "Value for " + key;
}
// Method for periodic cache update
public void refreshCache() {
// Logic for updating, e.g., loading all data and replacing cache content
}
}
This approach guarantees that when multiple threads request the same key simultaneously, the database load occurs only once, and other threads will receive the result from the cache.