Hi,

How do I pass the thread context to another thread?

I created a decorator for ExecutorService. It copies the context from
source thread and copy to the target thread.

I am not sure whether this is the right approach or not. I saw something
called ContextDataInjector but I don't understand the usage of it.

Decorator:

public class ThreadContextAwareExecutorService extends
AbstractExecutorService {

    private ExecutorService executorService;

    public ThreadContextAwareExecutorService(ExecutorService
executorService) {
        this.executorService = executorService;
    }

    @Override
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        Map<String, String> context = ThreadContext.getContext();
        Runnable wrappedCommand = () -> {
            ThreadContext.clearMap();
            ThreadContext.putAll(context);
            command.run();
        };
        executorService.execute(wrappedCommand);
    }

    // ignore other decorated methods
}

Sample code:

public class MainApplication {
    private static final Logger logger =
LogManager.getLogger(MainApplication.class);
    private static final ExecutorService executor = new
ThreadContextAwareExecutorService(ForkJoinPool.commonPool());

    public static void main(String[] args) throws Exception {
        ThreadContext.put("REQUEST-ID", UUID.randomUUID().toString());
        logger.info("message 1");
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()
-> {
            logger.info("message 2");
            return "hello";
        }, executor);
        future.get();
    }
}

Reply via email to