java / expert
Snippet
Asynchronous Context Propagation with TaskDecorator
When using @Async, ThreadLocal variables like MDC (Mapped Diagnostic Context) are lost. A TaskDecorator allows you to capture the context from the calling thread and apply it to the execution thread, ensuring trace IDs and logging context are preserved across asynchronous boundaries.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MdcTaskDecorator implements TaskDecorator {@Overridepublic Runnable decorate(Runnable runnable) {Map<String, String> contextMap = MDC.getCopyOfContextMap();return () -> {try {if (contextMap != null) MDC.setContextMap(contextMap);runnable.run();} finally {MDC.clear();}};}}
spring
Breakdown
1
MDC.getCopyOfContextMap()
Captures the current thread's diagnostic context before the task is delegated to a pool.
2
MDC.setContextMap(contextMap)
Sets the captured context on the worker thread just before the task executes.