Returning values from @Async methods

You can also return values from @Async methods. To be able to do that, we use Future. Consider the doThisAsynchronouslyAndReturnAValue method, which is defined as follows, in the AsyncTask class. We are making it return Future using new AsyncResult<>(sum):

@Async
Future < Long > doThisAsynchronouslyAndReturnAValue() {
IntStream.range(1, 100).forEach(x - > logger.info("AsyncTask With Return Value {}", x));
long sum = IntStream.range(1, 100).sum();
return new AsyncResult < > (sum);
}

We can run the doThisAsynchronouslyAndReturnAValue method from the TaskSchedulingApplication class. When we call the method, we get Future<Long> futureValue as the result. We can let the method continue executing asynchronously. When you need the result of the execution of the method, you can call futureValue.get(). This will cause the calling thread to wait for the doThisAsynchronouslyAndReturnAValue method to complete execution and return a value:

@Override
public void run(String...args) throws Exception {
asyncTask.doThisAsynchronously();
Future < Long > futureValue = asyncTask.doThisAsynchronouslyAndReturnAValue();
IntStream.range(1, 100).forEach(x - > logger.info("TaskSchedulingApplication {}", x));
logger.info("Sum is {}", futureValue.get());

}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset