The Java Future object is used to get the result of asynchronous computation which is performed by a parallel thread(Executors). We call Future.get() method and wait until result is ready. This example shows a non blocking way for retrieving result from Future. java-implement-java-non-blocking-futures.
NonBlockingExecutor executor = new NonBlockingExecutor(Executors.newSingleThreadExecutor());
NonBlockingFuture<Integer> future = executor.submitNonBlocking(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
return 1;
}
});
future.setHandler(new FutureHandler<Integer>() {
@Override
public void onSuccess(Integer value) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
}
@Override
public void onFailure(Throwable e) {
System.out.println(e.getMessage());
}
});
Thread.sleep(50000);
In this onSuccess() method is called after parallel execution is finish. The problem is onSuccess() method is not running on the main thread. I want to perform onSuccess() method on the main thread. How can i fix this. Thanks
This is supported with CompletableFutures.
CompletableFuture.runAsync(() -> {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
}).whenComplete((task, throwable) -> {
if(throwable != null) {
System.out.println(e.getMessage());
} else {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
}
});
The caveat here is that the future would run the whenComplete
task on the executing thread and not the submitting thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With