I am using log4j ThreadContext for tracing in a spring boot application. I have created an interceptor by implementing HandlerInterceptor which intercepts a request and then sets 'x' value in the ThreadContext map using ThreadContext.put("correlationId", 'x'). The value 'x' is retrieved from the request headers. After the request is completed I clear the ThreadContext using ThreadContext.clearMap(). The requirement is to see correlationId in the logs with every logger statement which is getting fulfilled.
public class RequestHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(
final HttpServletRequest request,
final HttpServletResponse response,
final Object handler)
throws Exception {
ThreadContext.put(CORRELATION_ID, request.getHeader(CORRELATION_ID_HEADER));
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
ThreadContext.clearMap();
}}
Now my question is what will be the behavior if multiple requests are made by multiple users simultaneously. Will the value of correlationId in ThreadContext map get replaced with every new request before the completion of older requests? If so, then what would be the correct implementation since if the values of correlationId is getting replaced before the request is completed then in the logs I would have incorrect correlationId logged. Any help would be appreciated.