Java ExecutorService不工作,但单独创建线程工作
我有一个RESTAPI,我应该从外部API获取大量数据。我决定尝试多线程来优化整个获取-解析-持久化周期。但是我在执行器服务方面遇到了麻烦(在此工作之前我没有使用过)。我正在分享课程和整个过程的相关部分Java ExecutorService不工作,但单独创建线程工作,java,multithreading,Java,Multithreading,我有一个RESTAPI,我应该从外部API获取大量数据。我决定尝试多线程来优化整个获取-解析-持久化周期。但是我在执行器服务方面遇到了麻烦(在此工作之前我没有使用过)。我正在分享课程和整个过程的相关部分 public class LogRetrievingService implements Runnable { CustomHttpClient client; public LogRetrievingService(CustomHttpClient client) {
public class LogRetrievingService implements Runnable {
CustomHttpClient client;
public LogRetrievingService(CustomHttpClient client) {
this.client = client;
}
@Override
public void run() {
Response response = client.invokeExternalApi();
parse(response.readEntity(bytes[].class);
}
//skipping parse() for brevity, it basically selects some columns and sends them to DBwriter
我的RESTAPI资源是这样的
public class LogRetrieverResource {
private CustomHttpClient client;
public LogRetrieverResource(CustomHttpClient client) {
this.client = client;
}
//this does not work
public void initLogRetrieval() {
ExecutorService service = Executors.newFixedThreadPool(4); //max_thread
for(int i = 0; i < 4; i++) {
service.submit(new LogRetrievingService (client));
}
}
//THIS WORKS
public void initLogRetrieval() {
for(int i = 0; i < 4; i++) {
Thread thread = new Thread(new LogRetrievingService(client));
thread.start();
}
}
}
只是试着去注意差异,不应该有太大的差异。首先在executor提交循环结束时添加
service.shutdown()
。然后你会做完全相同的事情
下一个问题是,异常的处理方式有点不同。executor服务将捕获所有异常。出于调试目的,您可以尝试
service.submit(
() -> {
try{
new LogRetrievingService (client).run();
} catch(Exception e){
//log the exception so you can see if anything went wrong.
}
});
这不是使用ExecutorService处理异常的方法,但是,您应该抓住提交的未来并使用它来处理任何错误。另外,我怀疑spring有一些工具来完成这类工作。在第二个示例中,您在主(请求)线程中运行这些可运行程序,没有涉及多线程。@michalk感谢您的输入,由于保密原因,我无法从IDE复制粘贴,因此我输入了一个错误。我已经修正了编辑中的错误。我基本上想了解我在RESTAPI中使用ExecutorService的方法是否有缺陷?我是第一次使用ExecutorService。感谢您的输入。以后更新问题时,请不要以使您已经收到的答案无效的方式编辑问题。这些问题和答案对访问网站的其他人有用,而不仅仅是对你。如果有人对你在示例中做错的事情做出反应,然后你编辑示例以纠正错误,这只会造成混乱。如果答案是正确的,但不完整(即,没有解决您的问题),那么最好在问题的末尾附加一个“更新”,显示您尝试了什么,并解释您仍然需要帮助的原因。@SolomonSlow谢谢,我以后会确保它。您好,您的代码片段帮助我找到了错误原因。我的SSO cookie未在各个线程中正确生成。我的代码现在可以用了,非常感谢。
service.submit(
() -> {
try{
new LogRetrievingService (client).run();
} catch(Exception e){
//log the exception so you can see if anything went wrong.
}
});