如何提高多线程性能

时间:2018-09-04 10:27:43

标签: java multithreading executorservice threadpoolexecutor executor

我在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) {
        }
    }

}

2 个答案:

答案 0 :(得分:3)

不要每次都创建和关闭executor,而是使用单例cached thread pool。由于重复创建线程是不必要的,expensive也是不必要的,线程池的好处是可以保持线程的存在。

答案 1 :(得分: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);