Malay Pandey
Malay Pandey

Reputation: 81

Log4j's ThreadContext clears the automatically

I am inserting a key into ThreadContext map at the start of the application like so,

protected void doFilterWrapped(ContentCachingRequestWrapper request,
      ContentCachingResponseWrapper response, FilterChain filterChain)
      throws ServletException, IOException {
    // some code...
    ThreadContext.put(Constants.REQUEST_ID, requestID);
    ThreadContext.put(requestID + Constants.HASH + "retryCount", "-1");
    // some more code...
  }

Now in someother class I am trying to update the value of key requestID + Constants.HASH + "retryCount" like so,

String key = ThreadContext.get(Constants.REQUEST_ID) + Constants.HASH + "retryCount";
      if (ThreadContext.containsKey(key)) {
        ThreadContext.put(key, String.valueOf(Integer.valueOf(ThreadContext.get(key)) + 1));
      } else {
        ThreadContext.put(key, "-1");
      }
      System.out.println("\n\n  " + ThreadContext.get(key) + " \n\n");

But it only works once and after that it is not able to find the key, i.e ThreadContext.containsKey(key) is false.

Can someone explain me what the problem is.

Upvotes: 1

Views: 1417

Answers (1)

Curt Combar
Curt Combar

Reputation: 11

Have you tried setting the thead context inheritable system property? In your app startup, add this line:

System.setProperty("isThreadContextMapInheritable", "true");

With this property enabled, child threads will inherit the thread context.

Upvotes: 1

Related Questions