Search code examples
concurrencyexecutorservicejava.util.concurrentcallablefork-join

Java fork join issue


I am learning fork-join technique in java and have written the following program. I am running a for loop (5 times) and I want to run the contents of the for loop in separate threads. This is happening correctly. The problem is that when all the threads are finished, I want a vector of size 5 and it must contain the result of execution of thread 1 at index 0, result of execution of thread 2 at index 1 ............ result of execution of thread 5 at index 4. I am cleanly visualize what I want to achieve but don't know the syntax for it.

Currently I just get 1 number in my vector.

import java.util.Random;
import java.util.Vector;
import java.util.concurrent.*;


public class App {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Vector<Integer> > futureResult = null;
        for(int i = 0; i < 5; i++){
            futureResult = executor.submit(new Callable<Vector<Integer> >(){
                @Override
                public Vector<Integer>  call() throws Exception {
                    Random random = new Random();
                    int duration = random.nextInt(4000);                    
                    Vector<Integer> v = new Vector<Integer>();
                    v.add(duration);
                    return v;
                }
            }); 
        }

        executor.shutdown();

        try {
            System.out.println(futureResult.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Solution

  • You're creating a new vector in every thread, without any connection with the shared memory. You could just pass the index to write on to every thread, and also change the vector to an array or something pre-allocated.

    Another option would be to allocate the 5 vector positions and send every Integer object to its thread.