Consider the service class below:-
//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.
}
}
Service class above has an ExecutorService
as field. If say, 100 concurrent requests on process
method, does remaining (100-1) requests need to wait for thread availability?
How to solve the request wait? One option I could think is, instantiate, use and shutdown ExecutorService
within process
method. However aren't thread pool is meant to be reused?
Another option would be run as new Thread(new FutureTask<>(() -> {return cs.getCustomer()}))
. Which one is correct way?
Updates:-
Based from comments and answers, the ExecutorService
meant to be reused and frequent new Thread
creation is expensive. Therefore another option is just run service call sequentially.