Why does ThreadLocal utility always return null in Spring MVC app?

廉价感情. 提交于 2019-12-06 09:48:57

问题


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:


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.



来源:https://stackoverflow.com/questions/7301794/why-does-threadlocal-utility-always-return-null-in-spring-mvc-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!