Do we need clear MDC after HTTP request in Spring

Łukasz Woźniczka picture Łukasz Woźniczka · Feb 23, 2017 · Viewed 7.3k times · Source

According to this answer thread local variable when we use thread local we should clear all variable in thread pool environment.

So basically I just want to confirm that when we are using MDC (Mapped diagnostic context) we also should clear MDC to aware memory leaks, is that true ?

So for instance :

@Configuration
public class WebConfig implements WebMvcConfigurer {
    public class HttpInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(final HttpServletRequest request,
                                 final HttpServletResponse response,
                                 final Object handler) {
            MDC.put(SESSION_ID, session_id);
        {

        @Override
        public void postHandle(final HttpServletRequest request,
                               final HttpServletResponse response,
                               final Object handler,
                               final ModelAndView modelAndView) {
           MDC.clear(); //WE SHOULD CLEAR MDC.... if not memory leaks ?
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MdcHandlerInterceptor());
    }
}

Answer

Kayaman picture Kayaman · Feb 23, 2017

Not for memory leaks, but to prevent retaining information between requests. You don't want your first request putting foo and your second request putting bar, ending up with foo bar instead of just bar.

Of course if you're always filling up only the same exact values (like remote IP, etc.), this couldn't happen, but better safe than sorry. You don't want to log bad information.

Note: the information that you put in one request is not always propagated to next requests, because they can be executed on other threads even for the same endpoint. That's why the issue may be overlooked as it doesn't reproduce reliably, especially in cases where you're overwriting most of the values.