JavaPythonTech blog contains various tools and skills for a developer. Java/Python Best Practices, Tools, Examples, Programming interview questions.

How to calculate the sum of numbers in list asynchronously?


We will be using ExecutorService from Executor framework and Future interface to make asynchronous calls.
We will be using Streams from Java 8 to calculate the sum of integers in the list.

import java.util.List;
import
java.util.concurrent.Callable;
import
java.util.stream.Collectors;

public class
SumCalculator implements Callable {

    List
inputList;

    public
SumCalculator(List inputList){
       
this.inputList = inputList;
   
}

   
@Override
   
public Integer call() throws Exception {
       
return inputList.stream().collect(Collectors.summingInt(i->i));
   
}
}

Let’s split the list to 2 sublist and pass them to two different threads so that the sum is calculated asynchronously and returned.

We will use future.get() to get the result from each thread and combine to get the final total.

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.stream.IntStream;



public class ListSumAsync {



    public static void main(String...args){

        ExecutorService executorService =

                Executors.newFixedThreadPool(2);



        List intList = new ArrayList<>();

        //Let us add 0 to 100 to a list

        IntStream.range(1, 11)

                .forEach(i -> intList.add(i));



        //Let's split the list to 2 lists and pass

        // it to two threads and combine the result

        SumCalculator calculator1 =

                new SumCalculator(intList.

                        subList(0,intList.size()/2));

        Future result1 =

                executorService.submit(calculator1);



        SumCalculator calculator2 =

                new SumCalculator(intList.subList(

                        (intList.size()/2),intList.size()));

        Future result2 =

                executorService.submit(calculator2);



        try {

            int total = result1.get().intValue()+

                    result2.get().intValue();

            System.out.println("Total sum: "+total);

        } catch (InterruptedException e) {

            e.printStackTrace();

        } catch (ExecutionException e) {

            e.printStackTrace();

        }

    }



}


Share:

No comments:

Post a Comment

Announcements

Will be posting twice a week on latest java libraries/frameworks which a developer needs to know in 2019.
Also will add the common errors and resolutions for the same.

Please feel free to comment if you need anything specific.

Recent Posts

Popular Posts

Search This Blog

Blog Archive

Powered by Blogger.

Contributors

Pages