0

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

Mohan
  • 3,893
  • 9
  • 33
  • 42

1 Answers1

0

It is likely that some other thread is adding more futures to your futuresResObj list while the execution is in the blocking loop waiting for all threads to finish, try to add some logging statements, also try to wait for the future outside the System.out.println something like this

System.out.println("futuresResObj list Size::::"+futuresResObj.size());
for(Future<ResponseObj> future: futuresResObj) {
    future.get();
 }

you may also test with future.isDone() method to get an idea of how these threads are behaving.

Hasson
  • 1,894
  • 1
  • 21
  • 25