Skip to content

Instantly share code, notes, and snippets.

@huantt
Last active February 6, 2020 02:07
Show Gist options
  • Save huantt/49f26c56699362755bee78a0090928d1 to your computer and use it in GitHub Desktop.
Save huantt/49f26c56699362755bee78a0090928d1 to your computer and use it in GitHub Desktop.
Combile Multiple Futures in Java + Async-http-client example
package app
import org.asynchttpclient.AsyncHttpClient
import org.asynchttpclient.Response
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import static org.asynchttpclient.Dsl.asyncHttpClient
import static org.asynchttpclient.Dsl.config;
class Runner {
public static void main(String[] args) {
AsyncHttpClient asyncHttpClient = asyncHttpClient(config().setConnectTimeout(TimeUnit.SECONDS.toMillis(1).toInteger()))
List<String> urls = [
"https://webhook.site/1647465b-c28f-4ffe-bbfe-5d3ad95ef994",
"https://webhook.site/1647465b-c28f-4ffe-bbfe-5d3ad95ef994?a=1"
]
CompletableFuture<Response>[] futures = new Completablefuture[2]
for (int i = 0; i < urls.size(); i++) {
futures[i] = asyncHttpClient.prepareGet(urls[i]).execute().toCompletableFuture()
}
CompletableFuture.allOf(futures)
.thenApply { return futures.collect { it.join() } }//Join when all futures have completed
.thenApply({ responses ->
//Do something with results
responses.each { println("Status code: " + it.statusCode) }
})
//Do something else while the above code is running
Thread.sleep(10000)
asyncHttpClient.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment