Chirota
Chirota

Reputation: 165

Sum of numbers in list using threads in java

Input is List of integers. I want to check if we can spawn say 10 threads to find the sum of integers. I know we can pass shared variable and do synchronize but is there any way to do it without synchronized block to reduce latency ? (possibly without using java.util.concurrent package classes ?)

Upvotes: 0

Views: 1430

Answers (1)

Adonis
Adonis

Reputation: 4818

If you are not modifying your list, you can organize your thread so that they read only a part of the List, and since it is only a read, it should work without synchronization, the following should work (adapt to your need):

public class Test {

    public static List<Integer> integers;
    public static void main(String[] args) {
        integers =new ArrayList<Integer>();
        integers.add(1);
        integers.add(3);
        integers.add(2);
        integers.add(6);
        ExecutorService executor = Executors.newCachedThreadPool();
        Test test = new Test();
        Future<Integer> subRes1 = executor.submit(test.new ListTask(0, 1));
        Future<Integer> subRes2 = executor.submit(test.new ListTask(2, 3));

        int total;
        try {
            total = subRes1.get() + subRes2.get();
            System.out.println(total);
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private class ListTask implements Callable<Integer>{

        private int start;
        private int end;

        public ListTask(int start, int end){
            this.start =start;
            this.end = end;
        }
        @Override
        public Integer call() throws Exception {
            // TODO Auto-generated method stub
            int subTotal = 0;
            for (int i = start; i <= this.end; i++){
                subTotal += integers.get(i);
            }
            return subTotal;
        }

    }


}

Output: 12

Upvotes: 1

Related Questions