考虑以下服务类别:
//Singleton service
public class InquiryService{
private final ExecutorService es = Executors. newSingleThreadExecutor();
private final CustomerService cs = new CustomerServiceImpl();
public String process(){
//Asynchronous calls to get info from CustomerService
Future<String> result = es.submit(()->{return cs.getCustomer()});
//Query database
//Perform logic et all
String customerName = result.submit.get();
//continue processing.
}
}
Run Code Online (Sandbox Code Playgroud)
上面的服务类具有一个ExecutorServiceas字段。如果说在process方法上有100个并发请求,那么剩下的(100-1)个请求是否需要等待线程可用性?
如何解决请求等待?我可以想到的一种选择是ExecutorService在process方法内实例化,使用和关闭。但是,线程池不是要重用吗?
另一个选项将作为运行new Thread(new FutureTask<>(() -> {return cs.getCustomer()}))。哪一种是正确的方法?
更新:-
根据评论和答案,ExecutorService要重用和频繁Thread创建新内容的成本很高。因此,另一个选择是依次运行服务调用。