0

I am trying to execute http request asynchronously with async-http-client (built on top of Netty). Below is the code

public void fetch() {

AsyncHttpClient asyncHttpClient = asyncHttpClient(config().setThreadFactory(new DefaultThreadFactory("thread-for-async-calls"));

BoundRequestBuilder request = asyncHttpClient.prepareGet("http://www.demo.com");

request.execute(new AsyncStateHandler())
.toCompletableFuture()
.thenCompose(res -> {
// process the response
});
 
}

My understanding is that when I am on thread, say "thread-1" and then call fetch() method, the asynchronous HTTP request will be executed on thread "thread-for-async-calls". Then I want to fetch the response and process the response back on the thread that called the fetch() method (in this case "thread-1") and not on the thread that completed the request.

Is this achievable?

Adil Waqar
  • 33
  • 1
  • 1
  • 9

1 Answers1

0

CompletableFuture's async methods allow you to provide your own Executor.

Given your example, you could

request.execute(new AsyncStateHandler())
.toCompletableFuture()
.thenComposeAsync(....) // Provider your own Executor here, for example your "thread-1"

Ying Cherry
  • 143
  • 1
  • 5