Java8 - CompletableFuture - Running methods in async call sequentially

So I have this code block:

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

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

Then it's being called asynchronously:


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. Is there a way that I can make sure the code happening on callSomeMethod is happening sequentially?

Edit: read that ForkJoinPool has a work-stealing algo, might that be the cause of the issue?

1 answer

  • answered 2022-01-19 17:51 Taylor

    read that ForkJoinPool has a work-stealing algo, might that be the cause of the issue?

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum