gpt4 book ai didi

java - 并发访问 ExecutorService

转载 作者:行者123 更新时间:2023-11-30 06:01:19 25 4
gpt4 key购买 nike

考虑以下服务类别:-

//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)个请求是否需要等待线程可用?

如何解决请求等待?我能想到的一种选择是,实例化、使用和关闭 ExecutorServiceprocess 内方法。但是线程池不是要重用吗?

另一个选项将作为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com