Thread Syncronization when using Async.function inside a Workflow

My Workflow has 2 components. One that can be executed parallely by multiple thread (here i’m invoking child workflows) and the second that needs to be thread safe (Here I’m analyzing the outpupts of childworkflows).

Below is the Simplified pseudo code.

class workflowImpl {
	void workflowMethod() {
		Async.function(this::someFunction); //Thread1
		Async.function(this::someFunction); //Thread2
		Async.function(this::someFunction); //Thread3
	}

	void someFunction() {
		String output = parallelBlock();
       		oneThreadAtaTime(output);
	}

	String parallelBlock() {
		return invokeChildWorkflow();
	}	

	void oneThreadAtaTime(String output) {
           		analyzeOutputsAndTakeDecissions();
	}
}

How to ensure oneThreadAtaTime function is executed by only one thread at a time? Is there a way in temporal as i’m not allowed to use native java thread operations inside workflows.

Note : parallelBlock() and oneThreadAtaTime() are coupled together. They can’t be separated so as to apply Async.function just on the parallelBlock

boolean oneAtaTime;

void oneThreadAtaTime(String output) {
     Workflow.await(()->!oneAtATime);
     oneAtaTime = true;
     try {
         analyzeOutputsAndTakeDecissions();
     } finally {
         oneAtaTime = false;
     }
}

Maxim,

What if the 3 threads execute Workflow.await at the same time?
Am I missing something?

Hi Maxim,

I think I am missing something here.

What prevents the 3 threads from executing the Workflow.await(()->!oneAtATime); at the same time?
If they do so, oneAtATime will be false for all the three. And all three will endup executing analyzeOutputsAndTakeDecissions() function.

Are we making the assumption that, as all the childworkflows will be executed by a single thread, there is no chance of all the 3 workflows completing at the same time?

Temporal uses cooperative multithreading. So only one thread is executing at a time until it is blocked on some Temporal SDK API like await. So in your example, it is not possible for all three threads to get unblocked at the same time and the function analyzeOutputsAndTakeDecissions will be executed by only one of them at the time.