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
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);
*/
.then()
.Promise.all()
.