When should non-asynchronous methods be approved?
The decision to continue does not differ from the solution to the previous problem. When did you decide to make the operation asynchronous (for example, using CompletableFuture ) against writing purely synchronous code? The same recommendations apply here.
If you just consume the result or use a termination signal to start another asynchronous operation, then this in itself is a cheap operation, and there is no reason not to use synchronous termination methods.
On the other hand, if you combine several lengthy operations, each of which will perform the async operation on its own, use the async completion methods.
If you are somewhere in the middle, trust your gut or just go in with asynchronous completion methods. If you do not coordinate thousands of tasks, then you will not add a lot of overhead.
Should you limit the use of non-asynchronous execution to short, well-defined code blocks that do not call other methods?
I would use them for operations that do not work for long. You do not need to limit their use to trivially short and simple callbacks. But I think you have the right idea.
If you use CompletableFuture , then you have decided that at least some operations in your code base require asynchronous execution, but presumably not all operations are asynchronous. How did you decide which should be asynchronous and which should not? If you apply the same analysis to continuations, I think that everything will be all right.
What happens if you have a block of code that calls other methods that also return CompletableFuture s? It may look cheap on the surface, but what happens if these methods also use a non-asynchronous call? Isn't that related to one long non-asynchronous block, which can become expensive?
Returning a CompletableFuture usually means that the main operation is scheduled asynchronously, so this should not be a problem. In most cases, I would expect the stream to look something like this:
- You synchronously call the async method that returns
CompletableFuture . He plans some async operation to ultimately provide the result. Your call returns almost immediately, without blocking. - Upon completion, you can call up one or more continuations. Some of them can cause additional asynchronous operations. Those will call methods that plan additional asynchronous operations, but, as before, they return almost immediately.
- Go to (2) or finish.