1

I have a static ThreadLocal object in my web application, where I am initializing with some default value in a web servlet filter class before processing the request. In the application, several other classes (like processors) uses and update its value. I have read in some articles that objects created with ThreadLocal are still associated with threads though the request process is completed as threads are maintained in a pool managed by container. This leads to memory leaks if the objects are not removed from ThreadLocal variable.

I have two questions in this context.

  1. Among the below options, which one is the best and proper way to remove its reference to prevent memory leaks.

    ThreadLocal obj;
    1) obj.remove(); // remove the contents of ThreadLocal.
    2) obj.set(""); // set some default value
    3) obj.set(null); // set null
    
kswaughs
  • 2,967
  • 1
  • 17
  • 21

1 Answers1

3

Use ThreadLocal#remove(). This is however not your main concern. Your main concern should be that you can guarantee that remove() is also invoked in exceptional cases. The correct way to do this is to perform the remove() in the finally of a try block where the TLS is created and delegated.

YourContext context = null;
try {
    context = YourContext.create(request, response);
    chain.doFilter(request, response);
} finally {
    if (context != null) context.release(); // Invokes remove().
}

If you're already on Java 7+, better yet is to let your context implement AutoCloseable whereby close() invokes remove() and then use a try-with-resources block.

try (YourContext context = YourContext.create(request, response)) {
    chain.doFilter(request, response);
}

For more hints as to how to create YourContext, head to Retrieving Web Session from a POJO Outside the Web Container.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I am still using Java 6 and In Filter class, I am initializing and removing before and after the chain call. Could you also help me with my second question ? – kswaughs Feb 29 '16 at 09:40
  • As answered, removing must happen in finally block. As to second question, you're supposed to ask one question per Question. GC matter is at least not related to TLS matter. If an object doesn't have any references, it's eligible for GC. Simple as that. – BalusC Feb 29 '16 at 09:44