Removing Thread locals after Context propagation

I am trying to implement a Custom context propagator using my own thread local and able to do so .
My question: Isn’t it required to remove the thread locals ?
If it’s required to do so ,then what are the places to do that?

I see that the example provided uses MDC and clears them inside WorkflowThreadImpl
However I dun see them getting cleared anywhere else .

I see that the example provided uses MDC and clears them inside WorkflowThreadImpl

Correct, this clears all MDC entries for the specific workflow thread.

Isn’t it required to remove the thread locals ?

You don’t have to clean MDC context but it’s good practice to do that. If you add to the context
it is responsibility of your code to do that in the end.

then what are the places to do that?

Are you using interceptors? I think would help to see some of your impl to be able to provide more info.

Yes ,I am using interceptors .
I will try to send a test case .I am thinking if you have multiple interceptors will context propagation have an impact depending upon which interceptor is removing the thread local ? In that case should always the last interceptor remove the thread locals ?

BTW. Use WorkflowThreadLocal instead of ThreadLocal and no cleanup is needed.

Thanks @maxim for this suggestion.
I tried your Suggestion .
The thing is I want to use context propagators across Client ,Workflows and Activities

So the moment I use WorkflowThreadLocal on the client side I get the error “Called from non workflow or workflow callback thread”

So I separated them to two different context propagators -One for Client that doesn’t use WorkflowThreadLocal and one for Workflows and Activities that use WorkflowThreadLocal.

I still get the same error primarily because of some logic inside RootWorkflowClientHelper that also deals with workflow context propagators .

Any suggestion how to separate them?

Unfortunately, ContextPropagagors indeed have the problem you outlined. I proposed WorkflowThreadLocal as you mentioned interceptors which can differentiate between workflow and activity code.

Thank you @maxim for confirming the same .I think what will help though is having an API to get WorkFlowInfo that doesn’t throw error (optional / just plain Null) in a non work flow context .Even if it throws error it should be properly categorised so that caller can check for cause. This way It will be possible to differentiate between client and work flow contexts.

The current implementation inside DeterministicRunnerImpl throws a generic Error that doesn’t help.

I agree. Would you file an issue to add the Workflow.isWorkflowThread method?

Here you go . A friendly api to know if the current Thread is running under Workflow Context · Issue #1321 · temporalio/sdk-java · GitHub

1 Like

It already exists as io.temporal.workflow.unsafe.WorkflowUsafe.isWorkflowThread