#3 Asynchronous Programming in Java-Launching Several Tasks Concurrently

anil gola
3 min readJun 18, 2023

--

This blog is a continuation of my previous blog:

https://medium.com/@anil.java.story/concurrent-vs-asynchronous-16a8323c9ccf

In our previous blog, we launched several tasks synchronously and checked the time it took. In this blog, we will also execute the same callables but concurrently in executor services and check their time. The callables are the same as shown below.

Callable<Quotation> fetchQuotationA = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-A");
};

Callable<Quotation> fetchQuotationB = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-B");
};

Callable<Quotation> fetchQuotationC = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-C");
};

Callable<Quotation> fetchQuotationD = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-D");
};

Callable<Quotation> fetchQuotationE = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-E");
};

We collected our tasks on a list.

Now we are going to submit our task to a pool of threads. Let’s create a pool of threads first.

Now, it’s time to submit our task to this executor service.

var futures = new ArrayList<Future<Quotation>>();
for(Callable<Quotation> task : taskList){
futures.add(executorService.submit(task));
}

Let’s collect the result of all this future now.

var quotations = new ArrayList<Quotation>();
for(Future<Quotation> future : futures){
quotations.add(future.get()); // blocking call
}

Now it’s just a classical stream question to find the best quotations.

var bestQuotation =  quotations.stream()
.min(Comparator.comparing(Quotation::getValue))
.orElseThrow();

Let’s wrap this operation in startInstant and endInstant, and the whole code will look like below:

 public static void run_concurrenlty() throws ExecutionException, InterruptedException {
Callable<Quotation> fetchQuotationA = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-A");
};

Callable<Quotation> fetchQuotationB = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-B");
};

Callable<Quotation> fetchQuotationC = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-C");
};

Callable<Quotation> fetchQuotationD = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-D");
};

Callable<Quotation> fetchQuotationE = () -> {
Thread.sleep(RandomUtils.nextInt(450,500));
return new Quotation(RandomUtils.nextInt(1,100),"server-E");
};

var taskList = List.of(fetchQuotationA,
fetchQuotationB,
fetchQuotationC,
fetchQuotationD,
fetchQuotationE );
var executorService = Executors.newFixedThreadPool(6);
var startInstant = Instant.now();

var futures = new ArrayList<Future<Quotation>>();
for(Callable<Quotation> task : taskList){
futures.add(executorService.submit(task));
}

var quotations = new ArrayList<Quotation>();
for(Future<Quotation> future : futures){
quotations.add(future.get()); // blocking call
}

var bestQuotation = quotations.stream()
.min(Comparator.comparing(Quotation::getValue))
.orElseThrow();
var endInstant = Instant.now();
System.out.println("Concurrently - Best Quotation is ["+ bestQuotation.value+"]"
+ " Best server is ["+bestQuotation.serverDescription+ "]"
+ " (millis) " + Duration.between(endInstant,startInstant).toMillis());
executorService.shutdown();
}

Now we will run both the synchronous method and the asynchronous method simultaneously.

Let’s check the result.

Clearly, we can see a difference of nearly 5 times less when executing our task concurrently. We have done better here. In the next blog, we will see how we can achieve the same with completion stage APIs in Java.

Next part:

https://medium.com/@anil.java.story/4-asynchronous-programming-in-java-launching-several-tasks-with-completionstage-apis-8da909e6266e

My youtube channel:

Asynchronous Programming : https://youtu.be/AHL2zuZ_5_k

--

--