I am creating 10 threads and adding 2 kinds of jobs to them as follows.
public class ParallelAdder {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Future<Integer>> list = new ArrayList<Future<Integer>>();
for (int i = 0; i < 10; i++) {
Future<Integer> future;
if (i % 2 == 0) {
future = executor.submit(new Call1());
} else {
future = executor.submit(new Call2());
}
list.add(future);
}
for(Future<Integer> fut : list) {
System.out.println("From future is "+fut.get());
}
}
}
class Call1 implements Callable<Integer> {
public Integer call() throws Exception {
System.out.println("Calling 1");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
}
}
class Call2 implements Callable<Integer> {
public Integer call() throws Exception {
System.out.println("Calling 2");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 20;
}
}
Call2 job returns faster as compared to Call1.
In my future list, I want the result of a job as soon as it completes. It should not depend on all others job to be done.
Here Call2 return is waiting for Call1. How to solve this?