Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java returning before tasks complete

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:

  1. Method A calls Method B
  2. Method 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)
  3. Method A returns before Method B finishes
like image 805
Kevin Wu Avatar asked Dec 24 '15 08:12

Kevin Wu


People also ask

Does a method end after return?

A 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.

How do you make a block of code asynchronous in Java?

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.

Can you have code after a return statement Java?

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.


1 Answers

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

like image 71
Prim Avatar answered Nov 06 '22 17:11

Prim