how to spwan recursive calls and for loop iterations in multiple threads in java (if possible)?

886 views Asked by At

I was wondering if it is possible to spawn each loop iteration (each iteration into a thread by itself) and finally collect the result. consider this example, nothing fancy in it at all. Just a simple for-loop, but the idea is to extend on it. The body of for loop does not matter, I just filled up with some code. but basically assume it has some expensive calculation which will take few minutes to complete for each iteration. so I want to do each loop calculation in a separate thread.

public class Threadspawns {

    private double[] arr = new double[4];

    public void calculations(){
        for (int i =2; i < 6; i++){
                   //expensive calculation
            arr[i-2]=Math.pow(i,500);
        }
    }

    public static void main(String[] args){
        Threadspawns t = new Threadspawns();
        long start = System.currentTimeMillis();
        t.calculations();
        long end = System.currentTimeMillis();
        System.out.println(Arrays.toString(t.arr));
        System.out.println("time taken "+ (end-start));

    }

}

on the same note, if it is possible to actually split the recursive calls into multiple threads and collect them as they return. Example is that of fibonacci

public static int fibonacci(int n){
        if (n==0)
            return 0;
        if (n==1)
            return 1;
        return fibonacci(n-2)+fibonacci(n-1);
    }

It is possible that it cannot be done for fibonacci recurive method. but any other example of paralleling recursive calls between threads IF POSSIBLE would be nice to know.

P.S: I have basic knowledge of Thread and Runnable, but wondering if the above is doable

1

There are 1 answers

0
Mak On BEST ANSWER

Solution to your first requirement that is moving the expensive calculation into a Callable task. Hope it find it useful:

import java.util.Arrays;
import java.util.concurrent.*;

public class Threadspawns {
    private final int THREAD_COUNT = 8;
    private final int CALCULATION_COUNT = 60000;
    private double[] arr = new double[CALCULATION_COUNT];

    public void calculations() {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
        ExecutorCompletionService<Double> completionService = new ExecutorCompletionService<Double>(executorService);
        for (int i = 2; i < CALCULATION_COUNT; i++) {
            completionService.submit(new Calculation(i));
        }

        //Get from all Future tasks till all tasks completed
        for (int i = 2; i < CALCULATION_COUNT; i++) {
            try {
                arr[i] = completionService.take().get();
            } catch (InterruptedException e) {
                e.printStackTrace();  //do something
            } catch (ExecutionException e) {
                e.printStackTrace();  //do something
            }
        }
    }

    private static class Calculation implements Callable<Double> {
        private final int num;

        private Calculation(int num) {
            this.num = num;
        }

        @Override
        public Double call() throws Exception {
            return Math.pow(num, 500);
        }
    }

    public static void main(String[] args) {
        Threadspawns t = new Threadspawns();
        long start = System.currentTimeMillis();
        t.calculations();
        long end = System.currentTimeMillis();
        System.out.println(Arrays.toString(t.arr));
        System.out.println("time taken " + (end - start));
    }
}