Maintaining order of execution in Async method calls

Hi Team,

I have this piece of code to execute two methods asynchronously so that I can receive signals meanwhile, but I also want to maintain the order these methods are executed.

List<Promise<Void>> acts = new ArrayList<>();
acts.add(Async.procedure(activities::uploadSignature, id, signature));
acts.add(Async.procedure(activities::submitSignature, id));

private CompletablePromise<Void> uploaded = Workflow.newPromise();
uploaded.completeFrom(Promise.allOf(acts));

Is there a way I can ensure uploadSignature is always called before submitSignature, while maintaining the async nature of the calls?

One way could be to have your activity invocations in order in a method of your workflow implementation, for example:

private void handleSignature(String id, Signature signature) {
      activities.uploadSignature(id, signature);
      activities.submitSignature(id);
}

and in your workflow code for example:

Async.procedure(this::handleSignature, id, signature);
1 Like

Another way I think could be just to use thenApply, for example:

Async.procedure(activities::uploadSignature, id, signature)
          .thenApply(
              v -> {
                activities.submitSignature(id);
                return v;
              });
1 Like

Thank you @tihomir for the solutions. This works!

Hi @tihomir, isn’t Activity considered a blocking call?
I’m asking because API doc of thenApply states that: Note that no blocking calls are allowed inside of the function.

The api doc that is referred in previous question is here.

We will update the comment to make it more clear. The intent was to say that the function code should follow the same constraints as the rest of the workflow code, outlined here.

So invoking an activity in the function passed to thenApply is fine (blocking and then resuming the workflow thread with things like activity invocation).

Hope that helps.

1 Like

Thank you @tihomir . I thought that maybe thenApply and thenCompose behave differently in that regard, as thenApply has this comment about blocking calls, and thenCompose does not (docs).
Thank you for the clarification.

1 Like

@mschielmann thanks for bringing this up!
@spikhalskiy already created PR for it!! https://github.com/temporalio/sdk-java/pull/1029

1 Like

@tihomir I really appreciate your fast feedback and reaction!
I’ve reviewed the MR and added a comment :slight_smile: