Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept of promises in Java

Is there a concept of using promises in java (just like ut is used in JavaScript) instead of using nested callbacks ?

If so, is there an example of how the callback is implemented in java and handlers are chained ?

like image 945
u009988 Avatar asked Jan 07 '23 00:01

u009988


1 Answers

Yep! Java 8 calls it CompletableFuture. It lets you implement stuff like this.

class MyCompletableFuture<T> extends CompletableFuture<T> {

   static final Executor myExecutor = ...;

   public MyCompletableFuture() { }

   public <U> CompletableFuture<U> newIncompleteFuture() {
       return new MyCompletableFuture<U>();
   }

   public Executor defaultExecutor() {
       return myExecutor; 
   }

   public void obtrudeValue(T value) {
       throw new UnsupportedOperationException();
   }
   public void obtrudeException(Throwable ex) {
       throw new UnsupportedOperationException();
   }
}

The basic design is a semi-fluent API in which you can arrange:
        (sequential or async)
        (functions or actions)
triggered on completion of
         i) ("then") ,or
        ii) ("andThen" and "orThen")
others. As in:

MyCompletableFuture<String> f = ...; g = ...
   f.then((s -> aStringFunction(s)).thenAsync(s -> ...);
or
   f.andThen(g, (s, t) -> combineStrings).or(CompletableFuture.async(()->...)....
like image 130
Debosmit Ray Avatar answered Jan 08 '23 15:01

Debosmit Ray