1

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.

1 Answers1

0

Are you working with blocking- or Non-blocking-IO (NIO)? If you are working with blocking-IO (which probably most of the applications used the last decades), then your server will create a thread for every request made by a user. Everything from accepting the request, your business logic in your service classes and making calls to other systems like databases or services are handled by that request (and is blocked while waiting for answers from these system).
The ThreadContext is managed on a per thread basis and so separated from other threads and requests.
If you are working with NIO, then things start to get more complicated, because then a request made by an user is handled by several threads.

lrxw
  • 3,576
  • 7
  • 32
  • 46