ExecutorCompletionService 整合了Executor和BlockingQueue的功能,可以用来完成基于多线程的监控。
示例:
ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletionService<String> completionService =
new ExecutorCompletionService<String>(executorService);
List<String> resultList = new ArrayList<String>();
completionService.submit(new Task("QuerySMS",querySmsServiceImpl,request,param));
completionService.submit(new Task("QueryMMS",queryMmsServiceImpl,request,param));
completionService.submit(new Task("QueryVoice",queryVoiceServiceImpl,request,param));
//
for(int i=0;i<counter;i++){
Future<String> future = completionService.take();
resultList.add(future.get());
}
private class Task implements Callable<String> {
private Service service;
private String queryType;
private ParamBean param;
private HttpServletRequest request;
public IntegratedTask(String queryType, Service service,
HttpServletRequest request,ParamBean param){
...
}
@Override
public String call() throws Exception {
return service.execute(request, param);
}
}
resultList存储的即是response。completionService会自动等待所有接口完后成再返回结果。
另外,也可以设置future的超时参数,进行超时处理。