0
 <service-activator ref="serviceName" input-channel="request-channel" method="methodName">
        <poller task-executor="taskExecutorCustom"/>
    </service-activator>
 <task:executor id="taskExecutorCustom" pool-size="5-20" queue-capacity="0"> 

can any one suggest how can I pass the MCD context to the method of service "serviceName"?

1 Answers1

1

The answer is to decorace a Runnable which is going to be performed on that TaskExecutor.

There are many article in the Internet on the matter:

How to use MDC with thread pools?

https://gist.github.com/pismy/117a0017bf8459772771

https://rmannibucau.metawerx.net/post/javaee-concurrency-utilities-mdc-propagation

Also Spring Security provides some solution how to propagate a SecurityContext from one thread to another: https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5/#concurrency

What I would suggest you to take some ideas from those links and use an existing API in the ThreadPoolTaskExecutor:

/**
 * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}
 * about to be executed.
 * <p>Note that such a decorator is not necessarily being applied to the
 * user-supplied {@code Runnable}/{@code Callable} but rather to the actual
 * execution callback (which may be a wrapper around the user-supplied task).
 * <p>The primary use case is to set some execution context around the task's
 * invocation, or to provide some monitoring/statistics for task execution.
 * @since 4.3
 */
public void setTaskDecorator(TaskDecorator taskDecorator) {

So, that your decorator should just have a code like this:

taskExecutor.setTaskDecorator(runnable -> {
        Map<String, String> mdc = MDC.getCopyOfContextMap();
        return () -> {
            MDC.setContextMap(mdc);
            runnable.run();
        };
    });
Artem Bilan
  • 113,505
  • 11
  • 91
  • 118