I have a method and it calls another method, for which the result is not important. To be exact, it is a POST request to a web service and the result is processed in that method and not in the calling method. Now I want the main method to return before that task finishes.
In essence, I need some sort of asynchronousity. What tools can I use in Java? Here are the steps again:
A
calls Method B
B
starts executing (we are not interested in the results of method b: it makes a call to a web service and processes the results itself)A
returns before Method B
finishesA return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function. For more information, see Return type.
We can use the submit method of the ExecutorService to perform the task asynchronously and return the instance of the FutureTask. Here we've used the isDone method provided by the Future interface to check if the task is completed. Once finished, we can retrieve the result using the get method.
We cannot write any code after return statement. If you are trying to compile with this code, compilation will fail. It is same for throwing exception. This is because after return or throwing exception statement the control will goes to the caller place.
You can use CompletableFuture.runAsync()
to call method B async.
You can add a callback by calling .thenRun()
on returned future if you want to do something when method B exited
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