ThreadLocal usage

The ThreadLocal is very helpful to keep some information available from anywhere in the application but it is very important to release it when the process ends, otherwise, the resource will never be free and can cause a memory leak.

Here is an example of using TheadLocal to store data in a web application. I define a filter to setup the content of the ThreadLocal and I use it later in a servlet.

First of all, I create a class to store the ThreadLocal:

package net.classnotfound.threadlocal.handler;

public class ThreadLocalHandler {
    private static ThreadLocal myThreadLocal = new ThreadLocal<>();
    
    public static void setData(final String value) {
        myThreadLocal.set(value);
    }
    
    public static String getValue() {
        return myThreadLocal.get();
    }

    public static void remove() {
        myThreadLocal.remove();
    }
}

Now, the filter which is responsible of initialization of the ThreadLocal content:

package net.classnotfound.threadlocal.filter;

import java.io.IOException;
[...]

@WebFilter(urlPatterns = "*")
public class ThreadLocalFilter implements Filter {

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        long time = new Date().getTime();
        ThreadLocalHandler.setData("this is the value: "+time);
        chain.doFilter(request, response);
        ThreadLocalHandler.remove();

    }

    @Override
    public void destroy() {
        ThreadLocalHandler.remove();
    }
} 

Note that the Threadlocal is initialized before calling the next filter (via the filterChain) and released after.

Now, when I want to use the value, I just need to do:

String value = ThreadLocalHandler.getValue();

Leave a comment