Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need clear MDC after HTTP request in Spring

Tags:

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());
    }
}
like image 966
Łukasz Woźniczka Avatar asked Feb 23 '17 11:02

Łukasz Woźniczka


People also ask

What does MDC clear do?

MDC. put() is used to add a key and a corresponding value in the MDC, while MDC. clear() empties the MDC.

Is MDC shared between threads?

Yes, MDC is thread-local.

What is the use of MDC in slf4j?

MDC is used to stamp each request. It is done by putting the contextual information about the request into the MDC. MDC class contain the following static methods: void put(String key, String val) : puts a context value as identified by key into the current thread's context map.

Is MDC ThreadLocal?

Internally, MDC uses ThreadLocal and it has some predefined functionalities like adding a prefix to every log.


1 Answers

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.

like image 182
Kayaman Avatar answered Sep 22 '22 09:09

Kayaman