ThreadLocal Resource Leak and WeakReference

后端 未结 7 1736
清酒与你
清酒与你 2020-12-30 03:12

My limited understanding of ThreadLocal is that it has resource leak issues. I gather this problem can be remedied through proper use of WeakReferences with ThreadLocal (al

7条回答
  •  失恋的感觉
    2020-12-30 03:39

    I realise this isn't strictly an answer to your question but as a general rule I won't suggest using a ThreadLocal in situration where there isn't a clear tear down at the end of a request/interaction. The classic is doing this sort of thing in a servlet container, at first glance it seems fine, but since the threads are pooled it becomes a issue with the ThreadLocal hanging onto the resource even after each request has been processed.

    Suggestions:

    1. Use a filter of similar wrapper for each interaction to clear the ThreadLocal at the end of each interaction
    2. You could use a alternative to SimpleDateFormat like FastDateFormat from commons-lang or Joda as somebody has already suggested
    3. Just create a new SimpleDateFormat every time you need it. Seems wasteful I know, but in most applications you just won't notice the difference

提交回复
热议问题