考虑以下服务类别:-
//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.
}
}
上面的服务类有 ExecutorService
作为字段。如果说 process
上有 100 个并发请求方法,剩余(100-1)个请求是否需要等待线程可用?
如何解决请求等待?我能想到的一个选择是实例化、使用和关闭ExecutorService
process
内方法。但是线程池不是要重用的吗?
另一个选项将运行为 new Thread(new FutureTask<>(() -> {return cs.getCustomer()}))
。哪一种方法是正确的?
更新:-
根据评论和回答,ExecutorService
意味着可重复使用和频繁新Thread
创作是昂贵的。因此,另一个选择是按顺序运行服务调用。
最佳答案
您的服务是单例
,这意味着在应用程序的整个运行时中仅存在一个实例(如果实现正确!)。因此,实际上您有一个 ExecutorService
处理 newFixedThreadPool(1)
。
does remaining (100-1) requests need to wait for thread availability?
哦,是的,所有 100-1 个其他请求都必须等待,因为第一个请求已经在线程池中的线程中执行。由于线程池的大小是固定的,因此它永远无法增长以处理其他请求。
How to solve the request wait?
您的线程池中需要更多线程来承担您的任务。
One option I could think is, instantiate, use and shutdown ExecutorService within process method
这确实是个坏主意。创建和销毁Thread
所花费的时间太多了。更多关于此here 。这就是使用ThreadPool
的整个想法。
Another option would be run as new Thread(new FutureTask<>(() -> {return cs.getCustomer()}))
构造一个new Thread()
。请阅读我之前的观点。
So, what is right!?
一种方法是使用 Executors.newFixedThreadPool(10)
,以便 (90-10) 个请求等待。可以吗?或者也许您正在寻找 newCachedThreadPool
!
警告:此外,请阅读有关在 ThreadPool
中使用 ThreadLocal
的副作用(如果适用)的信息。
关于java - 并发访问 ExecutorService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57904512/