In the Java SDK, is the workflow method guaranteed to be called only once in a particular instance of the workflow class?

I notice that when a Java workflow is started, first the workflow class constructor is called (of course), then maybe some of the signal method are called if there are some signals queued up, and then the workflow method in called.

It looks like the workflow method will only ever be called once within that particular instance of the workflow class? The workflow completes when the workflow method returns, and then if there’s another run of the workflow (such as perhaps with the same workflow id), the constructor is called again creating a new class instance.

Just wanted to double-check that my understanding was correct. Thank you!

Andrew

Yes, your understanding is correct. From the business point of view, the workflow method is going to execute exactly once.

Note that the underlying implementation uses replay to reconstruct the workflow state if needed. This means that in practice the workflow class can be instantiated many times and the workflow method invoked many times. You can see it by putting print statements into the workflow code and killing the workflow worker during the workflow execution. This replay adds the requirement that the workflow code must be deterministic.

It is important to not think about replay when writing your workflow code (besides ensuring that it is deterministic). So always treat the workflow code as exciting exactly once.

1 Like

I notice that when a Java workflow is started, first the workflow class constructor is called

Just wanted to add that with Java SDK in case of client signalWithStart call where an existing execution does not exist, the signal is delivered before the first WorkflowTaskScheduled event, so your signal handler method will be invoked before your workflow method.

1 Like

Thank you @maxim!

That is, for a particular run id, do I have that right? (With execution perhaps spread across several runs of the workflow worker, if the worker is restarted and the workflow replayed).

Yes, I understand the high-level logical concept, now just looking to be sure that my understanding of the low-level mechanics is correct :slight_smile:

From the point of view of the code, for a particular constructed instance of the workflow class in Java within a single run of the workflow worker, the workflow method will only ever be called once for that particular Java class instance, even in the presence of replay?

Thank you!

Yes, you are correct. For the given run id.

Yes, a particular instance is going to see a single call to the workflow method.

1 Like

Yes, I had noticed that as well :slight_smile: