Promise

12 Sep 2024 . java .

A promise is an object that may produce a single balue sometime in the future: either a resolved value or a reason that it’s not resolved(e.g. a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

The result of Promise can be set anytime because it has a public setter method. E.g. CompletableFuture and SettableFuture

// You trick your mom into creating you a promise of eventual donation
Supplier<Integer> momsPurse = ()-> {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            ;
        }

        return 100;

    };

ExecutorService ex = Executors.newFixedThreadPool(10);

// Mom's promise was created, but waited for some "completion" event
CompletableFuture<Integer> promise =  
CompletableFuture.supplyAsync(momsPurse, ex);

// You created such event, announcing your plans to thank your mom
promise.thenAccept(u->System.out.println("Thank you mom for $" + u ));

// Mom started open her purse...but very slow...
// Father interfered much faster and completed the promise instead of your mom
promise.complete(10);

Output:

Thank you mom for $10


Promise Vs Future


Future

The result of the future will set by an asynchronous computation. FutureTask must be initialized since there is no non-argument constructor.

  • Create a Future

      public class SquareCalculator {    
            
          private ExecutorService executor 
            = Executors.newSingleThreadExecutor();
            
          public Future<Integer> calculate(Integer input) {        
              return executor.submit(() -> {
                  Thread.sleep(1000);
                  return input * input;
              });
          }
      }
    
  • Consume a Future

      Future<Integer> future = new SquareCalculator().calculate(10);
        
      while(!future.isDone()) {
          System.out.println("Calculating...");
          Thread.sleep(300);
      }
        
      Integer result = future.get();
        
      /* Cancel code
       * boolean canceled = future.cancel(true); 
       */
    

Promise Vs callback

Advantages

  • Avoid callback hell which can be unreadable.
  • Write sequential asynchronous code that is readable with .then().
  • Write parallel asynchronous code with Promise.all().
  • With promises, these scenarios which are present in callbacks-only coding, will not happen:
    • Call the callback too early
    • Call the callback too late (or never)
    • Call the callback too few or too many times
    • Fail to pass along any necessary environment/parameters
    • Swallow any errors/exceptions that may happen

Disadvantages

  • Slightly more complex code.
  • In older browsers where ES2015 is not supported, you need to load a polyfill in order to use it.