In my singleton scoped service class below, all methods in the class require some user context that is known when Service.doA()
is called. Instead of passing around info across methods, I was thinking about storing those values in TheadLocal
. I have two questions about this approach:
1) Does the implementation below use ThreadLocal
correctly? That is, it is thread-safe and the correct values will be read/written into the ThreadLocal
?
2) Does ThreadLocal userInfo
need to be cleaned up explicitly to prevent any memory leaks? Will it be garbage collected?
@Service
public class Service {
private static final ThreadLocal<UserInfo> userInfo = new ThreadLocal<>();
public void doA() {
// finds user info
userInfo.set(new UserInfo(userId, name));
doB();
doC();
}
private void doB() {
// needs user info
UserInfo userInfo = userInfo.get();
}
private void doC() {
// needs user info
UserInfo userInfo = userInfo.get();
}
}