Sam
Sam

Reputation: 6890

Why do I get a duplicate Id in my MDC SLF4J for two requests?

I have a web application. My application deployed by Tomcat. I write a Servlet Filter for put some data in MDC class at SLF4J By following code:

MDC.put("Id", UUID.randomUUID().toString();

When I run my application for second or third request I get duplicate UUID. This scenario is serial and isn't concurrent. I think there exists a thread pool that thread context don't clear.

Upvotes: 2

Views: 1545

Answers (1)

durron597
durron597

Reputation: 32323

Use this structure to guarantee the ID is removed:

try {
    MDC.put("Id", UUID.randomUUID().toString());

    // The rest of your code
} finally {
    MDC.remove("Id");
}

(no catch block is necessary). This will guarantee that the Id key is removed for this transaction.

Also, of course Tomcat uses a Thread Pool, this is how it manages requests when they are concurrent. Further reading: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html

Upvotes: 2

Related Questions