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