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());
}
}
MDC. put() is used to add a key and a corresponding value in the MDC, while MDC. clear() empties the MDC.
Yes, MDC is thread-local.
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.
Internally, MDC uses ThreadLocal and it has some predefined functionalities like adding a prefix to every log.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With