Skip to content

Instantly share code, notes, and snippets.

@sirech
Created May 8, 2022 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirech/48d7c381e4bd1f89a1c432960c44af7c to your computer and use it in GitHub Desktop.
Save sirech/48d7c381e4bd1f89a1c432960c44af7c to your computer and use it in GitHub Desktop.
private T getAndCache(String key, Supplier<R> valueSupplier) {
/*
This has the disadvantage that the [get result, cache it] is not atomic. So if two requests try to update the same key at the same time, it might create an undetermined result.
However, two calls to the same service should return the same value, so we should be able to live with that.
This is not happening inside the compute method anymore due to problems acquiring the lock that led to significant timeouts.
*/
var result = valueSupplier.get();
if (result == null) {
return null;
}
return Try.of(() -> {
cache.save(result);
return result;
})
.recover(Exception.class, e -> {
log.error("Could not save result to cache", e);
return result;
})
.map(Cacheable::data)
.get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment