Suppliers.memoize should take an option to memoize exceptions
See original GitHub issueRelated Pull request to fix the documentation https://github.com/google/guava/pull/2916 has been merged.
If the delegate in the Suppliers.memoize throws an exception on calling get() then further calls to the get() method of the Memoized suppliers still goes to the delegate. With the pull request the Javadocs clarify that there is a danger that the underlying delegate could be called more than once.
What we need is a method with the following signature
Suppliers.memoize(Supplier<T> delegate, boolean memoizeExceptions)
By default the single argument memoize method could delegate to the above method with a “false” flag i.e, exceptions are NOT memoized by default. However if true is passed then even when the delegate throws an exception, that exception is stored by the memoized supplier and is re-thrown everytime it is called.
Use cases where this can be used
- A class X uses a memoized Supplier the delegate talks to an external Paypal like service or a configuration service. When the delegate fails we do not want to retry the external service (until such time as we have a notification that the external service is back up in which case class X re-initializes the supplier)
- A class X has a memoized supplier with expiration of 5 seconds and wants an absolute guarantee that even in the case of failures the underlying delegate is NEVER called more than once in 5 seconds.
I am happy to contribute a patch if this new API is accepted.
Issue Analytics
- State:
- Created 6 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
As original requestor of this issue and having read Guava guideline that “If you find something is missing in guava, you should log a request and do your own thing” that is exactly what I did.
In general I agree it is perhaps not a good idea to store an exception as a member variable which we have to store if we are to throw the exact exception. In my code I have done exactly that. As @tkruse points out if that is a problem you can store a boolean variable to throw some generic exception message.
The key problem here is that the original purpose of protecting an underlying resource from being flooded is actually made more worse by Guava as it gives the impression to the developer that it is a good idea to wrap expensive calls into this method. If not already done this should at least be clarified in the javadoc to avoid confusion.
I wonder if a useful generalization of this advice is, “don’t threat Throwable instances as data.”