I have a java method that needs to be execute in parallel with different set of input's(from list). Basically my business logic method has some external call logic that consumes little amount of time to respond. In order to reduce my overall time to get my final response,i tried to invoke this method in parallel using Future and @ Async implementation. Below is my sample code:
Controller Class:
List<Future<ResponseObj>> futuresResObj = new ArrayList<Future<ResponseObj>>();
Future<ResponseObj> report = null;
for(int i=0 ; i<idList.size() ; i++){
request.setId(idList.get(i));
System.out.println("i Value::::"+i);
report = parallelService.executeBusinessMethod(request,i);
futuresResObj.add(report);
}
System.out.println("futuresResObj list Size ::::"+futuresResObj.size());
for(Future<ResponseObj> future: futuresResObj) {
System.out.println(future.get().getResObj()); // concurrent access excpetion throws here.
}
My Service Class:
@Service
public class ParallelService {
@Autowired
Properties properties;
@Async
public Future<ResponseObj> executeBusinessMethod(RequestObj request , int count) throws InterruptedException,Exception {
System.out.println ("Start executeBusinessMethod:::: "+count);
ResponseObj responseObj=null;
// Do invoke many external calls( Consumes little time to complete).
return new AsyncResult<ResponseObj>(responseObj);
}
}
But the above implementation doesn't work like what I expected and does not return all the responses.Getting timeouts and broken calls.
Is there any other way to accomplish the above goal..? Please help me on this..!
Framework : Spring 4.0.9.RELEASE