-
Hello, I know I can use a simple ConcurrentHashMap but I want to leverage the power off caffeine. Note: I started my journey trying to use Guava, but guavaAsyncLoader forces you to implement Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
In these cases it is typically better to forgo a caching library and use a scheduled task to periodically replace an unmodifiable map. This is simple to reason about, works as desired, and requires no dependencies. For example, private volatile Map<String, String> cityToState;
CsvCache(ScheduledExecutorService executor) {
executor.scheduleAtFixedRate(this::reload, 10, 10, TimeUnit.MINUTES);
reload();
}
private reload() {
cityToState = parseCsv().stream()
.collect(toUnmodifiableMap(row -> row.get("city"), row -> row.get("state"));
}
public Optional<String> getStateForCity(String city) {
return Optional.ofNullable(cityToState.get(city));
} |
Beta Was this translation helpful? Give feedback.
In these cases it is typically better to forgo a caching library and use a scheduled task to periodically replace an unmodifiable map. This is simple to reason about, works as desired, and requires no dependencies. For example,