google / guava

Google core libraries for Java
Apache License 2.0
50.27k stars 10.92k forks source link

`Suppliers.memoize` should have some mechanism for memoizing results only conditionally (based on a `Predicate`) #3101

Open tgdavies opened 6 years ago

tgdavies commented 6 years ago

In the case that my supplier is impure -- e.g. it is caching an external resource which may fail, I would like to be able to create a memoization which will retry failure -- e.g.

Supplier<Option<T>> Suppliers.retryableMemoize(Supplier<Option<T>> supplier)

So the memoization is only done when the wrapped supplier returns a non-empty Option

cpovirk commented 6 years ago

I see that you also posted on #2928. Are you asking for something slightly different here?

PierceHanley commented 6 years ago

2928 was about preserving the original thrown exception, and re-throwing it each subsequent time the Supplier is invoked. This seems to be specific to suppliers of Optionals: asking to be able to wrap them such that it will be invoked until the first time it returns a "present" Optional, then that value is memoized for the future and the wrapped supplier won't be invoked again.

Not weighing in on whether that's a worthwhile use case, just clarifying what I believe @tgdavies is asking for.

tgdavies commented 6 years ago

Yes -- @PierceHanley is correct.

tgdavies commented 6 years ago

Perhaps: Supplier<T> memoizeConditionally(Supplier<T> supplier, Predicate<T> condition)

cpovirk commented 6 years ago

Ah, sorry -- somehow I saw only the title of this and completely missed that it had a body. Thanks.

We've had some discussions of a feature like this in the context of common.cache, but I don't think we've taken any action :\ (Possibly Caffeine did?) Given our lack of action there (and on similar issues like https://github.com/google/guava/issues/872), you'll probably be best served by rolling your own. Maybe we'll be able to get to some of these someday if we bundle them all together into a larger new feature.