I am writing a library that offers several asynchronous methods that return CompletableFutures. The library has an internal thread pool for executing the computational work of the asynchronous methods.
I want to make sure the following two requirements are met:
- the returned CompletableFuture is NOT completed by an internal thread so that CompletableFuture chains external to my library are never executed by the library's internal thread pool
- all computations of my asynchronous method are executed by the internal thread pool and NOT by the user thread (i.e. the thread of the method caller)
So say the library has the following blocking method
Data request(Address address) {
Message request = encode(address);
Message response = sendAndReceive(request);
Data responseData = decode(response);
return responseData;
}
and a corresponding asynchronous method
CompletableFuture<Data> requestAsync(Address address) {
return CompletableFuture.supplyAsync(() -> encode(address), internalThreadPool)
.thenCompose(request -> sendAndReceiveAsync(request))
.thenApply(response -> decode(response));
}
The first requirement is met by adding chaining .whenCompleteAsync((v,t) -> {}) as explained in this answer.
But what needs to be done to meet the second requirement?