如何提高多线程的性能

问题描述 投票:1回答:2

我用google搜索并找到了使用多线程的最佳方法,但它失败了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) {
        }
    }

}
java multithreading executorservice threadpoolexecutor executor
2个回答
3
投票

不要每次创建和关闭executor,使用单身cached thread pool。由于重复创建线程是不必要的和expensive,并且线程池的好处是保持线程存在。


1
投票

哇所有这些在列表上异步迭代?

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

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);
© www.soinside.com 2019 - 2024. All rights reserved.