Java – ThreadLocal (and singleton) in EJB container
I wrote an authorization system that relies on objects representing the current user To simplify programming and improve performance, I want to save these objects in ThreadLocal after the user logs in
It looks like this:
public class UserCache { private static final ThreadLocal<User> cache = new ThreadLocal<User>(); public User getCurrentUser() { return cache.get(); } public void setCurrentUser(User user) { cache.set(user); } }
I've read that static elements make clustering a problem If I have a usercache on each cluster node, they all have their own cache objects that are out of sync with the cache objects on other nodes yes? Usercache is a classic candidate for singleton because an application needs only one instance of it But as far as I know, @ singleton EJBs have the same behavior in the cluster
So how to make usercache cluster in EJB 3.1 (Java EE 6) environment?
Solutions extracted from answers:
>JVM clustering using CDI's sessionscope (JSR 299) or > using terracotta
Solution
Now that you are using Java EE 6, using CDI (context and dependency injection) will not be so easy This will allow user information to be placed in the session scope and easily injected anywhere CDI manages the rest for you