Search code examples
javaservletshttprequestthread-local

When would it be advised to use a ThreadLocal singleton instead of a request attribute?


If my ThreadLocal singleton is only going to be alive for the life of the request anyhow, then why not just use a request attribute? Is this just an easy way to get at a context in a single thread without having to pass through or get to the request object?


Solution

  • My opinion is, that using a request attribute is more preferable than using a ThreadLocal variable.

    It makes code cleaner and you don't have to worry about cleaning the ThreadLocal (as it might be re-used be in context of another request which re-uses the same thread).

    Though, properly designed and coded local request storage via ThreadLocal is fine, if usage of ThreadLocal is encapsulated and you don't simply share an instance between different classes (and it's life-cycle is properly handled).