Hacker News new | ask | show | jobs
by joshlemer 698 days ago
I faced this issue once. I solved it by creating a wrapping/delegating Executor, which would capture the MDC from the scheduling thread at schedule-time, and then at execute-time, set the MDC for the executing thread, and then clear the MDC after the execution completes. Something like...

    class MyExecutor implements Executor {
        private final Executor delegate;
        public MyExecutor(Executor delegate) {
            this.delegate = delegate;
        }
        @Override
        public void execute(@NotNull Runnable command) {
            var mdc = MDC.getCopyOfContextMap();
            delegate.execute(() -> {
                MDC.setContextMap(mdc);
                try {
                    command.run();
                } finally {
                    MDC.clear();
                }
            });
        }
    }