【发布时间】:2018-09-04 10:27:43
【问题描述】:
我用谷歌搜索并找到了使用多线程的最佳方法,但它失败了 100 条记录它给出了 504 状态代码。下面的代码有什么改进的余地吗?
@Scheduled(fixedRate = 5000)
public ResponseEntity<Object> getData(List<JSONObject> getQuoteJson, String username,
String authorization) throws ParseException, IOException, Exception {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "*");
CompletableFuture<JSONArray> future = null;
JSONArray responseArray = new JSONArray();
try {
executor = Executors.newFixedThreadPool(getQuoteJson.size());
for (int i = 0; i < getQuoteJson.size(); i++) {
JSONObject jsonObject = (JSONObject) getQuoteJson.get(i);
future = CompletableFuture.supplyAsync(() -> {
JSONObject response = asynCallService.getDataAsyncService(jsonObject, productCode, authorization);
responseArray.add(response);
return responseArray;
}, executor);
}
return new ResponseEntity<Object>(future.get(), responseHeaders, HttpStatus.OK);
} catch (Exception e) {
throw e;
} finally {
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (Exception e) {
}
}
}
【问题讨论】:
-
在旁注中:“我已经 [...] 找到了使用多线程的最佳方法”是我会非常谨慎的声明。没有使用多线程的最佳方法。对于特定用例,通常甚至没有明确的“最佳方式”。
-
developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 for the unititiated
-
鉴于 504 与 网关 相关,它是否来自您在多线程代码中调用的服务?
-
responseArray.add(response);在未来体内使用可能不是线程安全的。
标签: java multithreading executorservice threadpoolexecutor executor