如何提高多线程的性能



我已经用谷歌搜索并找到了使用多线程的最佳方法,但它在 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) {
}
}
}

不要每次都创建和关闭executor,请使用单一实例缓存线程池。由于重复创建线程是不必要的且昂贵的,线程池的好处是保持线程存在。

哇,所有这些都是为了只在列表上迭代异步?

我认为这更有可能是您搜索的内容:

HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "*");
final JSONArray responseArray = new JSONArray();
getQuoteJson.parallelStream().map(e->asynCallService.getDataAsyncService(e, productCode, authorization)).forEach(responseArray::add);
return new ResponseEntity<Object>(responseArray, responseHeaders, HttpStatus.OK);

相关内容

  • 没有找到相关文章

最新更新