I use Executor.newSingleThreadScheduled Executor() to do a very simple repetitive task which works great.
But because it is in another thread, I lose the correlation_Id that is in my ThreadContext and the logs created by the child thread are incomplete...
How can I push my correlation_Id to the child thread?
To propagate the correlation ID from the parent thread to the child thread and ensure that the logs created by the child thread contain the necessary information, you can make use of Java's
InheritableThreadLocalclass.Here's an example of how you can push the correlation ID to the child thread:
In the above code, we use an
InheritableThreadLocalvariable calledcorrelationIdto store the correlation ID. This class allows values to be inherited by child threads automatically.When the main thread sets the correlation ID using
correlationId.set(generateCorrelationId()), the value is automatically propagated to the child thread.In the child thread, we retrieve the correlation ID using
correlationId.get()and use it to perform the task or include it in the logs.By using
InheritableThreadLocal, the correlation ID will be accessible in the child thread, allowing you to maintain the necessary context and ensure complete logs.