简体   繁体   English

Java8 - CompletableFuture - 在异步调用中按顺序运行方法

[英]Java8 - CompletableFuture - Running methods in async call sequentially

So I have this code block:所以我有这个代码块:

 someMethod(SomeParameter someParameter) {
  for (SomeObject: object) {
    if (someObject is true) {
      callSomeMethod(someParameter);
    } else {
      callSomeMethodInstead(someParameter);
    }
  }
}

callSomeMethod(SomeParameter someParameter) {
  someObjectdataFromDb = getFromDB(someId);
  boolean checker = checkIfNull(someObjectdataFromDb ) || checkIfHasCertainStatus(someObjectdataFromDb );
  if (checker) {
    callAnExternalAPI(someParameter);
  }
}

Then it's being called asynchronously:然后它被异步调用:

CompletableFuture.runAsync{()->{someMethod(someParameter);}}

Now, the issue is that the team owning the external API is telling us that we're making multiple calls at them at the same time resulting to some issues on creating the data.现在,问题在于拥有外部 API 的团队告诉我们,我们同时对它们进行多次调用,从而导致创建数据时出现一些问题。 Is there a way that I can make sure the code happening on callSomeMethod is happening sequentially?有没有一种方法可以确保callSomeMethod上发生的代码是按顺序发生的?

Edit: read that ForkJoinPool has a work-stealing algo, might that be the cause of the issue?编辑:读到 ForkJoinPool 有一个工作窃取算法,这可能是问题的原因吗?

read that ForkJoinPool has a work-stealing algo, might that be the cause of the issue?读到 ForkJoinPool 有一个工作窃取算法,这可能是问题的原因吗?

Doubt it, any kind of thread pool would allow for multiple of this to be executed concurrently.怀疑它,任何类型的线程池都允许同时执行多个线程池。

If you need to make sure it's only being invoked one-at-a-time, you could make callSomeMethod synchronized (assuming it's either static or on a singleton object).如果您需要确保它一次只被调用一次,您可以使callSomeMethod同步(假设它是 static 或 singleton 对象)。 Note that this means things block indefinitely, so make sure you have appropriate timeouts in the interaction with the external service.请注意,这意味着事情会无限期地阻塞,因此请确保您在与外部服务的交互中有适当的超时。

If you have more sophisticated needs, for example can allow some limited concurrency (like up to 3 at a time is fine but no more or similar), or are looking for timeouts, I'd suggest using a resilience4j bulkhead , I've used that for this purpose quite successfully.如果您有更复杂的需求,例如可以允许一些有限的并发性(比如一次最多 3 个很好,但没有更多或类似的),或者正在寻找超时,我建议使用弹性 4j 隔板,我用过为此目的相当成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM