[英]ExecutorService does not work but individually creating threads work
我有一個 REST API,我應該在其中從外部 API 獲取大量數據。 我決定嘗試多線程來優化整個 fetch-parse-persist 循環。 但是我在使用ExecutorService
時遇到了麻煩(在這項工作之前我沒有使用過它)。 我正在分享整個過程的課程和相關部分
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
我的 REST API 資源是這樣的
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();
}
}
}
現在,當我點擊我的資源時什么也沒有發生,我可以看到客戶端的日志被點擊但它沒有去獲取數據。 但是,如果在我的LogRetrieverResource
類的循環內,我使用相同的 run 方法創建了一個新的Thread
實例,那么多線程數據獲取將按預期工作。 有人可以指出我做錯了什么嗎? 除了實現Runnable
接口方法之外,我之前沒有在 Java 中使用多線程的經驗。
編輯:添加客戶端類詳細信息
import javax.ws.rs.client.Client;
public class CustomHttpClient {
public Response invokeExternalAPI() {
return client
.target("url") //removing url for confidentiality
.request()
.accept(MediaType.APPLICATION_JSON)
.cookie("SSO",<token>)
.get();
}
}
只是試圖注意到差異,不應該有太大差異。 首先在執行程序提交循環的末尾添加service.shutdown()
。 然后你幾乎會做完全相同的事情。
下一個問題,異常的處理方式有點不同。 執行程序服務將捕獲所有異常。 出於調試目的,您可以嘗試。
service.submit(
() -> {
try{
new LogRetrievingService (client).run();
} catch(Exception e){
//log the exception so you can see if anything went wrong.
}
});
但這不是使用 ExecutorService 處理異常的方法,您應該獲取您提交的未來並使用它來處理任何錯誤。 另外,我懷疑 spring 有一些工具可以完成此類工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.