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.
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.