Skip to content

Preload data from CSV and refresh after Xmin. #898

Answered by ben-manes
xhadev asked this question in Q&A
Discussion options

You must be logged in to vote

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));
}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by ben-manes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants