Is it good practice to share workflow data between @WorkflowMethod and @UpdateMethod by using instance variables?

Let’s say I have this workflow interface

@WorkflowInterface
public interface IPlanWorkflow {
  @WorkflowMethod
  void run(IPlanWorkflowInput input);
  @UpdateMethod
  boolean applyPlanApprovalDecision(PlanApprovalDecision decision);
}

In the @UpdateMethod I want to run some activities that read data produced by activities executed in the @WorkflowMethod and also write data that other activities in the @WorkflowMethod will read once the @UpdateMethod is completed.
Is it good practice to use instance variables to share data between the two “scopes”?

public class PlanWorkflow implements IPlanWorkflow{
  Plan planningActivityOutput = null;
  PlanApprovalDecision decision = null;
  // ... activity stubs omitted...

  @WorkflowMethod
  void run(IPlanWorkflowInput input) {
     this.plan = planningActivity.createPlan(input);
     Workflow.await(() -> Objects.nonNull(planApprovalDecision));   
     // do something with planApprovalDecision value
};
  @UpdateMethod
  boolean applyPlanApprovalDecision(PlanApprovalDecision decision) {
  // try catch and lock unlock omitted for brevity
    if (this.plan.matchesConditionFromDecision(decision)) {
       // do something 
       this.planApprovalDecision = decision;
       return true;
    }

  }
}

Yes, using instance fields is the recommended approach for sharing data between different workflow functions.

Also, be aware of more advanced features. The workflow safe analog of Java ThreadLocal is WorkflowThreadLocal. And workflow safe way analog of global variables is WorkflowLocal.

1 Like