gpt4 book ai didi

Java:使用 ExecutorService 并行调用 API getList

转载 作者:行者123 更新时间:2023-12-01 19:50:24 24 4
gpt4 key购买 nike

我尝试加快并行调用两个 API 的代码速度。

第一个是

List<String> A = aService.getListA();
List<Integer> B = bService.getListB();

现在我将其更改为并行调用,如下所示:

ExecutorService es = Executors.newFixedThreadPool(2);
Future<List<String>> getAs = es.submit(() -> aService.getListA());
Future<List<Integer>> getBs = es.submit(() -> bService.getListB());
es.shutdown();

它似乎工作正常,但我不确定这段代码是否完美以及在这种情况下会发生什么,例如,如果 getListB() 从不回答。

编辑:int 更改为 Integer

最佳答案

It seems to work alright, but I'm not sure if this code is perfect and what would happen in case , for example, if getListB() never answers.

回答第二部分:在这种情况下,您的 future 对象就坐在那里,并且任何时候您调用 isDone() 时,它都会向您返回false。 p>

换句话说:如果您想使用某种超时,那么您可以在接收该 future 的级别上执行此操作。另一方面,它也可以进入该服务类别。含义:服务本身知道超时,并有某种方式将其传达给用户。

实际决定哪个选项在您的情况下“最好”,主要取决于您的设计的其余部分以及设计应满足的要求。因此:我们无法评估什么最适合您

关于Java:使用 ExecutorService 并行调用 API getList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51475125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com