I'm using Callable and ExecutorService to use multi-threading in my application.
In case if any Exceptions are thrown from one thread need to stop all threads even though it's work completed and need to throw that exception to the calling class method. For this, I used a shutDownNow() method.
Is this the right way? or any other effective ways there?
ExecutorService exSvc = Executors.newFixedThreadPool(5);
exSvc.setKeepAliveTime(60, TimeUnit.SECONDS);
List<Future<Integer>> futureList = new LinkedList();
for(int i=0; i<50;i++){
futureList.add(exSvc.submit(
new Callable<Integer>() {
public Integer call() throws Exception{
int num = new Random().nextInt(1000);
if(num==500){
throw new Exception("Error");
}
return num;
}
}));
}
for(int i=0; i<50; i++){
try {
int value = futureList.get(i).get();
} catch (Exception e) {
exSvc.shutdownNow();
throw new Exception("Error");
}
}