Video in progress

What is ThreadLocal, and when is it used?

ThreadLocal stores a separate value for each thread: one variable, but every thread sees its own copy. It is mostly used for request context (user, trace id) or for objects that are not thread-safe.

📖 Answer

public final class RequestContext {
    private static final ThreadLocal<String> USER = new ThreadLocal<>();

    public static void set(String user) { USER.set(user); }
    public static String get() { return USER.get(); }
    public static void clear() { USER.remove(); }
}

You set in a filter and clear in a finally at the end of the request. Then you don't have to carry the user around as a parameter in the service layer. Spring's SecurityContextHolder, the way @Transactional binds a connection, and logback's MDC all work like this.

An old example: SimpleDateFormat is not thread-safe, so people kept it inside ThreadLocal.withInitial(...). Now DateTimeFormatter is immutable, and there is no need for that.

The main risk is forgetting remove(). In a thread pool, threads are reused, and the next request can see the previous user's value. That is both a bug and a security hole.