Class SingleFlight


  • public class SingleFlight
    extends Object
    SingleFlight implements call deduplication for equal keys.

    Example:

     public Result expensiveOperation(final Parameters parameters) throws Exception {
         return singleFlight.execute(parameters, new Callable<Result>() {
             @Override
             public Result call() {
                 return expensiveOperationImpl(parameters);
             }
         });
     }
    
     private Result expensiveOperationImpl(Parameters parameters) {
         // the real implementation
     }
     
    • Constructor Detail

      • SingleFlight

        public SingleFlight()
    • Method Detail

      • execute

        public <V> V execute​(Object key,
                             Callable<V> callable)
                      throws Exception
        Execute a Callable if no other calls for the same key are currently running. Concurrent calls for the same key result in one caller invoking the Callable and sharing the result with the other callers.

        The result of an invocation is not cached, only concurrent calls share the same result.

        Parameters:
        key - A unique identification of the method call. The key must be uniquely identifiable by it's Object.hashCode() and Object.equals(Object) methods.
        callable - The Callable where the result can be obtained from.
        Returns:
        The result of invoking the Callable.
        Throws:
        Exception - The Exception which was thrown by the Callable. Alternatively a InterruptedException can be thrown if the executing Thread was interrupted while waiting for the result.