anupampunith
anupampunith

Reputation: 167

Java CompletableFuture get Method

I am having some trouble understanding CompletableFuture. I do not understand the get() method. Please correct me if I am wrong, but it says "Waits if necessary for this future to complete, and then returns its result." So If I do not return any result I do not have to call get method? Please see below. Even I do not call get() method it still does its job. So I understand get() as if the future returns something it will make sense then, otherwise get() is not necessary for a future that does not return anything.

//Since it does not return something two statements below do the same thing.

CompletableFuture.runAsync(doSomething()); 
CompletableFuture.runAsync(doSomething()).get(); 

private final CompletableFuture<Void> doSomething() {
 //do something 
    return null;
}

Upvotes: 2

Views: 2949

Answers (1)

Beri
Beri

Reputation: 11600

The main purpose of get() is to wait for the task to complete, then return the result.

If your task is a Runnable, not Callable, it will return a Void, so as you have pointed out, there is no point in checking the result. For such tasks you are executing get() only to wait for them to complete.

The main advantages of CompletableFuture are the methods that allow you to handle exceptions, and further process the data. It also has methods wo wait for all and single task to complete from a set of ComplatableFuture tasks. So it's mutch easyer to work in multithread anv. get() method works same as for Future class though.

UPDATE:

If you don't require for them to complete before passing further in your application, you don't have to call get() method at all. But it would be wise to keep a reference to them, and wait for them to complete or cancel them before exiting a program. At some point of the program you probably will want to see if they have completed.

But if you want for the to complete before going further, then you can use CompletableFuture.allOf().

In some cases it's also wise to add a timeout to their execution, so that you will not have a hanging thread in your application. This may be dangerous, especially on mobile environment.

So it all depends on your business case.

Upvotes: 2

Related Questions