Send Multiple Requests Concurrently in Java: Implement CompletableFuture

Asynchronous programming in Action

Modern life is fast.
We eat fast food, demand faster internet, shorter delivery times and instant news. So modern applications need to be fast.
Fast and reliable.

final CompletableFuture<Double> futureBTCtoEURO = getRate(BTC,EURO);
final CompletableFuture<Double> futureBTCtoCHF = getRate(BTC, CHF);
private CompletableFuture<Double> getRate(int fromCurrency, int toCurrency) {
return CompletableFuture.supplyAsync(() -> sendRequest(fromCurrency, toCurrency))
.exceptionally(exception -> {
System.err.println(exception);
return 0d;
});
}
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureBTCtoEURO, futureBTCtoCHF);
combinedFuture.get();

double basicBTCtoEURO = 0;
double basicBTCtoCHF = 0;
if (!futureBTCtoEURO.isCompletedExceptionally() && futureBTCtoEURO.isDone()) {
basicBTCtoEURO = futureBTCtoEURO.get();
}
if (!futureBTCtoCHF.isCompletedExceptionally() && futureBTCtoCHF.isDone()) {
basicBTCtoCHF = futureBTCtoCHF.get();
}
String getBestRate() {

int BTC = 189;
int EURO = 17;
int CHF = 4;

double basicBTCtoEURO = 0;
double basicBTCtoCHF = 0;

final CompletableFuture<Double> futureBTCtoEURO = getRate(BTC, EURO);
final CompletableFuture<Double> futureBTCtoCHF = getRate(BTC, CHF);

// allOf :: waits to complete features futureBTCtoEURO,futureBTCtoCHF
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureBTCtoEURO, futureBTCtoCHF);
try {
combinedFuture.get();//get: blocking method, waits all futures to be completed

if (!futureBTCtoEURO.isCompletedExceptionally() && futureBTCtoEURO.isDone()) {
basicBTCtoEURO = futureBTCtoEURO.get();
}
if (!futureBTCtoCHF.isCompletedExceptionally() && futureBTCtoCHF.isDone()) {
basicBTCtoCHF = futureBTCtoCHF.get();
}

} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return findMin(basicBTCtoEURO, basicBTCtoCHF);
}
@Test
public void sendMultipleRequests(){
CompletableFutureImpl fut = new CompletableFutureImpl();
String currency = fut.getBestRate();
System.out.println( " Buy " + currency);
Assert.assertNotNull(currency);
}
Let's get started!
getRate :fromCurrency 189 to currency 17
sending
getRate :fromCurrency 189 to currency 4
sending
getRate :fromCurrency 189 to currency 17 response {"data":[[{"currency_ID":17,"basic":"34910.1","reverse":"0.0000286","digits":1}]]}
getRate :fromCurrency 189 to currency 4 response {"data":[[{"currency_ID":4,"basic":"36053.4","reverse":"0.0000277","digits":1}]]}
Buy EURO

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store