Why does ThreadLocal utility always return null in

2019-04-14 18:43发布

I wrote this utility class to save temporary data in a Spring MVC app:

public abstract class FooUtil {

    private static final ThreadLocal<String> threadFoo = new ThreadLocal<String>();

    public static String getFooId(){
        return threadFoo.get();
    }

    public static void setFooId(String fooId){
        threadFoo.set(fooId);
    }

    public static void removeFooId(){
        threadFoo.remove();
    }

}

So I call FooUtil.setFooId("foo").

But when I later call FooUtil.getFooId(), it always returns null.

Do I need a constructor? Or maybe this shouldn't be an abstract class? I don't know.

1条回答
Animai°情兽
2楼-- · 2019-04-14 19:17

You need to call getFooId from the same thread as setFooId. This way you get the same result. I would log the thread name when you set and get values to see if they are the same.

查看更多
登录 后发表回答