【问题标题】:How to improve performance of multi threading如何提高多线程的性能
【发布时间】: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) {
        }
    }

}

【问题讨论】:

  • 在旁注中:“我已经 [...] 找到了使用多线程的最佳方法”是我会非常谨慎的声明。没有使用多线程的最佳方法。对于特定用例,通常甚至没有明确的“最佳方式”。
  • 鉴于 504 与 网关 相关,它是否来自您在多线程代码中调用的服务?
  • responseArray.add(response); 在未来体内使用可能不是线程安全的。

标签: java multithreading executorservice threadpoolexecutor executor


【解决方案1】:

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

【讨论】:

  • 嗨,孙,你能帮我深入一点吗?
  • @Soham 请检查答案中的链接。创建线程很昂贵,您可以使用缓存线程池来避免它。所以你不需要每次都创建executor = Executors.newFixedThreadPool(getQuoteJson.size());。你可以只持有一个全局执行器。
【解决方案2】:

哇,这一切都在一个列表上异步迭代?

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

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多