简体   繁体   中英

When should a method return CompletableFuture?

What are the general guidelines on when should a method return CompletableFuture? Suppose there are two classes A and B, where class B has a method performTask() which does a lot of IO, and class A invokes the performTask() method In Java one can write the multi-threaded code using the following approaches :

  • Let the caller of the method decide whether to execute a method asynchronously using ThreadPool. In this case, A will call the performTask() method asynchronously so that class B doesn't need to make its methods asynchronous.
  • Let the method performTask() return a Future or CompletableFuture so that class A simply calls performTask().

What are the general guidelines on which approach is the recommended approach?

The short answer

You decide.

The little bit longer answer

It depends:

  • When you know that callers will more often than not want to wait for performTask() to finish, make the method synchronous.

  • When you know that callers will more often than not want to continue doing stuff immediately after calling performTask() , and either not care about the result, or check it later, make the method asynchronous.

  • When you don't know, see the short answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM